# DeFindex > This file is very large and may be truncated. For an index of this content, please refer to https://docs.defindex.io/llms.txt instead. # USDC from Base with CCTP and Crossmint Source: https://docs.defindex.io/advanced-documentation/crossmint-cctp Move native USDC from Base or another EVM chain to a Crossmint Stellar smart wallet with Circle CCTP, then deposit it into a DeFindex vault. ## When to use this path Your users hold USDC in Crossmint smart wallets on Base (or another EVM chain that Circle CCTP supports) and you want that USDC earning yield in a DeFindex vault. DeFindex vaults run on Stellar, so the USDC has to cross first. Circle's Cross-Chain Transfer Protocol (CCTP) burns USDC on the source chain and mints the same USDC on Stellar. There is no wrapped token and no liquidity pool in the middle: what lands in the wallet is the same USDC that DeFindex USDC vaults accept. | | CCTP (this page) | Sodax ([Crossmint Smart Wallets](/integration-guide/guides-and-tutorials/crossmint-smart-wallets)) | | - | - | - | | Mechanism | Burn on the source chain, Circle attestation, mint on Stellar | Intent filled by a solver through the Sodax hub | | Asset received | Native USDC issued by Circle | USDC delivered by the solver | | Fee | Standard Transfer is free; Fast Transfer charges a fee per route, read from Circle's API | Solver and bridge fees in the quote | | Steps you run | Burn on the EVM chain, poll the attestation, call `mint_and_forward` on Stellar | Quote, submit, wait for the intent to be filled | | Use it when | You want native USDC and no third-party liquidity | You need an asset or route CCTP does not cover | The Crossmint setup is the same in both: one server key registered as `adminSigner` on an EVM smart wallet and on a Stellar smart wallet, and every transaction sent through Crossmint's REST API. If you have not set that up yet, start with the [reference repository](https://github.com/defindex-io/crossmint-defindex-guide) and the [Crossmint Smart Wallets guide](/integration-guide/guides-and-tutorials/crossmint-smart-wallets). ## The flow ```mermaid theme={null} sequenceDiagram participant S as Your server participant CM as Crossmint API participant B as Base (TokenMessengerV2) participant I as Circle Iris API participant F as Stellar CctpForwarder participant W as Stellar smart wallet (C...) participant V as DeFindex vault S->>CM: approve USDC to TokenMessengerV2 (EVM wallet) S->>CM: depositForBurnWithHook, destination domain 27 CM->>B: burn USDC S->>I: GET /v2/messages/6?transactionHash=... I-->>S: message + attestation (status complete) S->>F: mint_and_forward(message, attestation) F->>W: mint USDC and forward to the wallet S->>CM: contract-call deposit on the vault (Stellar wallet) CM->>V: deposit(amounts_desired, amounts_min, from, invest) ``` 1. **Burn on Base.** The Crossmint EVM smart wallet approves USDC to Circle's `TokenMessengerV2` and calls `depositForBurnWithHook` with destination domain `27` (Stellar). `mintRecipient` and `destinationCaller` are the Stellar `CctpForwarder` contract, and the hook data carries the address of the user's Stellar smart wallet. 2. **Attestation.** Circle's attestation service (Iris) signs the burn. You poll it until the message is `complete`. 3. **Mint and forward on Stellar.** Anyone can call `mint_and_forward(message, attestation)` on `CctpForwarder`. In one Soroban invocation it mints the USDC to itself and transfers it to the address in the hook data. 4. **Deposit.** The Stellar smart wallet deposits the USDC into a DeFindex vault, the same way as any other deposit from a Crossmint wallet. > [!CAUTION] > > On the burn, `mintRecipient` and `destinationCaller` must both be the `CctpForwarder` contract. Circle states that if either is wrong the funds are **permanently stuck and cannot be recovered**. Never put the user's wallet address in `mintRecipient`: it goes only in the hook data. See [CCTP on Stellar](https://developers.circle.com/cctp/references/stellar#use-cctpforwarder-for-stellar-recipients). ## Addresses and parameters Every value below comes from Circle's documentation, linked next to it. Read them from Circle's pages again before going to mainnet: Circle's own instructions are to look addresses up rather than hardcode them. ### Mainnet | Item | Value | Source | | - | - | - | | CCTP domain, Base | `6` | [Supported chains and domains](https://developers.circle.com/cctp/concepts/supported-chains-and-domains) | | CCTP domain, Stellar | `27` | [Supported chains and domains](https://developers.circle.com/cctp/concepts/supported-chains-and-domains) | | `TokenMessengerV2`, Base | `0x28b5a0e9C621a5BadaA536219b3a228C8168cf5d` | [Contract addresses](https://developers.circle.com/cctp/references/contract-addresses) | | USDC, Base | `0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913` | [USDC contract addresses](https://developers.circle.com/stablecoins/usdc-contract-addresses) | | `CctpForwarder`, Stellar | `CBZL2IH7F6BIDAA3WBNXYKIXSATJGMSW7K5P5MJ6STX5RXN47TZJDF5T` | [CCTP Stellar contracts](https://developers.circle.com/cctp/references/stellar-contracts) | | `TokenMessengerMinter`, Stellar | `CAE2G5Z77UP7GYPYGFOWFGW7C7J6I4YP2AFGSADRKQY62SYUFLPNFTXL` | [CCTP Stellar contracts](https://developers.circle.com/cctp/references/stellar-contracts) | | `MessageTransmitter`, Stellar | `CACMENFFJPJMSDAJQLX4R7K3SFZIW2LJSE3R2UMLGSWHFHS353FVXAZV` | [CCTP Stellar contracts](https://developers.circle.com/cctp/references/stellar-contracts) | | USDC, Stellar (asset) | `USDC-GA5ZSEJYB37JRC5AVCIA5MOP4RHTM335X2KGX3IHOJAPP5RE34K4KZVN` | [USDC contract addresses](https://developers.circle.com/stablecoins/usdc-contract-addresses) | | USDC, Stellar (contract) | `CCW67TSZV3SSS2HXMBQ5JFGCKJNXKZM7UQUWUZPUTHXSTZLEO7SJMI75` | Stellar Asset Contract of the asset above, see [Contract Deployments](/contract-deployments) | | Attestation API | `https://iris-api.circle.com` | [Get messages](https://developers.circle.com/api-reference/cctp/all/get-messages-v2) | ### Testnet | Item | Value | Source | | - | - | - | | `TokenMessengerV2`, Base Sepolia | `0x8FE6B999Dc680CcFDD5Bf7EB0974218be2542DAA` | [Contract addresses](https://developers.circle.com/cctp/references/contract-addresses) | | USDC, Base Sepolia | `0x036CbD53842c5426634e7929541eC2318f3dCF7e` | [USDC contract addresses](https://developers.circle.com/stablecoins/usdc-contract-addresses) | | `CctpForwarder`, Stellar testnet | `CA66Q2WFBND6V4UEB7RD4SAXSVIWMD6RA4X3U32ELVFGXV5PJK4T4VSZ` | [CCTP Stellar contracts](https://developers.circle.com/cctp/references/stellar-contracts) | | Attestation API | `https://iris-api-sandbox.circle.com` | [Get messages](https://developers.circle.com/api-reference/cctp/all/get-messages-v2) | > [!NOTE] > > Crossmint `staging` runs on `base-sepolia` and Stellar testnet. The reference repository's Sodax example uses a Crossmint test token on Base Sepolia; CCTP burns only Circle's testnet USDC listed above. ## Step by step The snippets reuse the `CrossmintRestClient` and helpers from [`defindex-io/crossmint-defindex-guide`](https://github.com/defindex-io/crossmint-defindex-guide): `getOrCreateEvmWallet`, `getStellarWalletAddress`, `sendTransactionAndGetHash`, `getStellarDepositBalance` and `depositToDefindexVault`. They use `ethers` v6 for EVM encoding and `@stellar/stellar-sdk` for Stellar. ### 1. Configuration ```typescript theme={null} // Circle CCTP, mainnet. Sources in the table above. export const cctp = { baseDomain: 6, stellarDomain: 27, baseTokenMessengerV2: "0x28b5a0e9C621a5BadaA536219b3a228C8168cf5d", baseUsdc: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", stellarCctpForwarder: "CBZL2IH7F6BIDAA3WBNXYKIXSATJGMSW7K5P5MJ6STX5RXN47TZJDF5T", irisApi: "https://iris-api.circle.com", }; export const stellar = { rpcUrl: process.env.STELLAR_SOROBAN_RPC_URL ?? "https://mainnet.sorobanrpc.com", networkPassphrase: "Public Global Stellar Network ; September 2015", // Funded classic account (G...) that pays the fee of mint_and_forward. See step 5. relayerSecret: process.env.STELLAR_RELAYER_SECRET!, }; ``` ### 2. Get both wallets The EVM wallet holds the USDC to move. The Stellar wallet is a Soroban smart contract wallet, so its address is a `C...` contract address. That address is the final recipient of the USDC. ```typescript theme={null} import { CrossmintRestClient } from "./shared/crossmint-rest.js"; import { config } from "./shared/config.js"; const rest = new CrossmintRestClient(config.apiKey, config.baseUrl); const { address: evmWallet } = await rest.getOrCreateEvmWallet(); // 0x... const stellarWallet = await rest.getStellarWalletAddress(); // C... ``` ### 3. Build the hook data These two helpers are Circle's, from [CCTP on Stellar](https://developers.circle.com/cctp/references/stellar#building-forwarder-hook-data-example). The forwarder is encoded as the raw 32 bytes of its contract ID. The recipient goes in the hook data as its full strkey text. ```typescript theme={null} import { StrKey } from "@stellar/stellar-sdk"; function contractStrkeyToBytes32(strkey: string): `0x${string}` { if (!StrKey.isValidContract(strkey)) { throw new Error(`Invalid contract strkey: ${strkey}`); } return `0x${Buffer.from(StrKey.decodeContract(strkey)).toString("hex")}`; } // bytes 0-23 zero, 24-27 version (0), 28-31 recipient length, 32+ recipient strkey (UTF-8) function buildCctpForwarderHookData(forwardRecipientStrkey: string): `0x${string}` { const isValid = StrKey.isValidEd25519PublicKey(forwardRecipientStrkey) || StrKey.isValidContract(forwardRecipientStrkey) || StrKey.isValidMed25519PublicKey(forwardRecipientStrkey); if (!isValid) throw new Error(`Invalid forward recipient: ${forwardRecipientStrkey}`); const recipientBytes = Buffer.from(forwardRecipientStrkey, "utf8"); const hookData = Buffer.alloc(32 + recipientBytes.length); hookData.writeUInt32BE(0, 24); hookData.writeUInt32BE(recipientBytes.length, 28); recipientBytes.copy(hookData, 32); return `0x${hookData.toString("hex")}`; } const forwarderBytes32 = contractStrkeyToBytes32(cctp.stellarCctpForwarder); const hookData = buildCctpForwarderHookData(stellarWallet); // the Crossmint C... address ``` ### 4. Approve and burn on Base through Crossmint Both calls are ordinary EVM transactions from the Crossmint smart wallet: `POST /transactions`, sign the approval message with the `adminSigner` key, `POST /approvals`, poll for `onChain.txId`. `sendTransactionAndGetHash` in the reference repository does all of that. The parameters of `depositForBurnWithHook` are from Circle's [contract interfaces](https://developers.circle.com/cctp/references/contract-interfaces#depositforburnwithhook). The amount is in Base USDC units, 6 decimals. ```typescript theme={null} import { ethers } from "ethers"; const erc20 = new ethers.Interface([ "function approve(address spender, uint256 amount) returns (bool)", ]); const tokenMessenger = new ethers.Interface([ "function depositForBurnWithHook(uint256 amount, uint32 destinationDomain, bytes32 mintRecipient, address burnToken, bytes32 destinationCaller, uint256 maxFee, uint32 minFinalityThreshold, bytes hookData)", ]); const amount = ethers.parseUnits("100", 6); // 100 USDC on Base // 4a. Allow TokenMessengerV2 to pull the USDC await rest.sendTransactionAndGetHash( evmWallet, { to: cctp.baseUsdc, data: erc20.encodeFunctionData("approve", [cctp.baseTokenMessengerV2, amount]), }, "base" ); // 4b. Burn, Standard Transfer: maxFee 0, minFinalityThreshold 2000 const burnTxHash = await rest.sendTransactionAndGetHash( evmWallet, { to: cctp.baseTokenMessengerV2, data: tokenMessenger.encodeFunctionData("depositForBurnWithHook", [ amount, cctp.stellarDomain, // 27 forwarderBytes32, // mintRecipient = CctpForwarder cctp.baseUsdc, // burnToken forwarderBytes32, // destinationCaller = CctpForwarder 0n, // maxFee 2000, // Standard Transfer hookData, ]), }, "base" ); ``` > [!TIP] > > **Fast Transfer.** Base supports Fast Transfer as a source chain (`minFinalityThreshold` `1000`), which shortens the wait from the Base finality window to seconds for a fee. Read the current fee for the route from `GET /v2/burn/USDC/fees/6/27` on the Iris API (`minimumFee` in basis points, entry with `finalityThreshold` `1000`) and set `maxFee` from it with a small buffer. Circle asks integrators not to hardcode the fee. See [CCTP fees](https://developers.circle.com/cctp/concepts/fees). Gas on Base: Crossmint sponsors gas for wallet transactions by default and bills it to your project in production. See [Crossmint gas sponsorship](https://docs.crossmint.com/wallets/guides/gas-sponsorship). ### 5. Wait for the attestation and mint on Stellar Poll Circle's [`GET /v2/messages/{sourceDomainId}`](https://developers.circle.com/api-reference/cctp/all/get-messages-v2) with the burn transaction hash until `status` is `complete`. The source domain is Base (`6`), not Stellar. ```typescript theme={null} interface AttestationMessage { message: string; // 0x-prefixed hex attestation: string; // 0x-prefixed hex status: string; } async function waitForAttestation(burnTxHash: string): Promise { const url = `${cctp.irisApi}/v2/messages/${cctp.baseDomain}?transactionHash=${burnTxHash}`; while (true) { const res = await fetch(url); if (res.ok) { const data = (await res.json()) as { messages?: AttestationMessage[] }; const msg = data.messages?.[0]; if (msg?.status === "complete") return msg; } else if (res.status !== 404) { console.warn(`Iris ${res.status}: ${await res.text()}`); } await new Promise((r) => setTimeout(r, 5000)); // Iris rate limit is 40 req/s } } const attestation = await waitForAttestation(burnTxHash); ``` Circle's Forwarding Service, which submits the destination transaction for you, does not support Stellar as a destination. Your backend submits `mint_and_forward` itself. `CctpForwarder` is publicly callable, so any funded Stellar account can pay the fee: the minted USDC goes to the address in the hook data, not to the caller. This is Circle's `submitSorobanTx` pattern from the [Stellar quickstart](https://developers.circle.com/cctp/quickstarts/transfer-usdc-stellar-arc), signed with a relayer account your server controls. ```typescript theme={null} import { Contract, Keypair, TransactionBuilder, rpc, xdr } from "@stellar/stellar-sdk"; async function mintAndForward(att: AttestationMessage): Promise { const server = new rpc.Server(stellar.rpcUrl); const relayer = Keypair.fromSecret(stellar.relayerSecret); const account = await server.getAccount(relayer.publicKey()); const messageBytes = Buffer.from(att.message.replace("0x", ""), "hex"); const attestationBytes = Buffer.from(att.attestation.replace("0x", ""), "hex"); const tx = new TransactionBuilder(account, { fee: "10000000", networkPassphrase: stellar.networkPassphrase, }) .addOperation( new Contract(cctp.stellarCctpForwarder).call( "mint_and_forward", xdr.ScVal.scvBytes(messageBytes), xdr.ScVal.scvBytes(attestationBytes) ) ) .setTimeout(120) .build(); const sim = await server.simulateTransaction(tx); if (rpc.Api.isSimulationError(sim)) throw new Error(`Simulation failed: ${sim.error}`); const prepared = rpc.assembleTransaction(tx, sim).build(); prepared.sign(relayer); const sent = await server.sendTransaction(prepared); if (sent.status === "ERROR") throw new Error(`Send failed: ${JSON.stringify(sent)}`); let result = await server.getTransaction(sent.hash); while (result.status === "NOT_FOUND") { await new Promise((r) => setTimeout(r, 2000)); result = await server.getTransaction(sent.hash); } if (result.status !== "SUCCESS") throw new Error(`mint_and_forward failed: ${sent.hash}`); return sent.hash; } const mintTxHash = await mintAndForward(attestation); ``` > [!NOTE] > > To keep a single signing path, you could also send `mint_and_forward` as a Crossmint `contract-call` from the Stellar smart wallet. Crossmint's [custom Stellar transactions](https://docs.crossmint.com/wallets/guides/send-transaction-stellar) guide passes `args` as a JSON object and does not document how to pass Soroban `Bytes`, so this page uses a plain relayer account. Confirm the encoding with Crossmint before taking that route. ### 6. Deposit into the vault The wallet now holds USDC with 7 decimals. Read what actually arrived and deposit it. ```typescript theme={null} const VAULT = process.env.DEFINDEX_VAULT_ADDRESS!; // a USDC vault const balance = await getStellarDepositBalance(stellarWallet); // USDC, 7 decimals if (balance === 0n) throw new Error("USDC not in the wallet yet"); const depositTxHash = await depositToDefindexVault(rest, stellarWallet, VAULT, balance); ``` `depositToDefindexVault` sends a Crossmint `contract-call` to the vault's `deposit` method with `amounts_desired`, `amounts_min` (0.5% slippage), `from` set to the smart wallet, and `invest: true`. The parameters mean the same as in [Deposit](/integration-guide/vault-operations/deposit) and in [Vault Methods](/advanced-documentation/direct-contract-calls/vault-methods#deposit). The DeFindex API's deposit endpoint returns an unsigned transaction for a classic account to sign, while a Crossmint smart wallet signs through Crossmint, which is why the reference repository calls the vault method directly. Use the API for everything that only reads, such as the position: `GET /vault/{address}/balance` ([Get balance](/integration-guide/vault-operations/get-balance)). > [!WARNING] > > `invest: true` on a vault that has never invested leaves the deposit idle until the manager runs one rebalance. See [Deposit with `invest: true` stays idle](/integration-guide/troubleshooting#deposit-with-invest-true-stays-idle). ## Stellar specifics **Precision.** USDC has 6 decimals on Base and every other CCTP chain, and 7 on Stellar. The CCTP message `amount` is always in 6-decimal units, and the mint on Stellar multiplies it by 10: `100000000` (100 USDC) burned on Base becomes `1000000000` on Stellar. Use 7 decimals for every amount you pass to the vault. In the other direction, a burn from Stellar ignores the seventh decimal and leaves it in the wallet. Source: [USDC precision for CCTP and Stellar](https://developers.circle.com/cctp/references/stellar#usdc-precision-for-cctp-and-stellar). **Address encoding.** CCTP messages carry 32 bytes per address with no type prefix, so the protocol cannot tell an account (`G...`) from a contract (`C...`) and assumes `mintRecipient` is a contract. That is why the mint goes to `CctpForwarder` and the real recipient travels as a strkey in the hook data. Source: [Stellar address types](https://developers.circle.com/cctp/references/stellar#stellar-address-types). **Contract wallets need no trustline.** A Crossmint Stellar wallet is a contract (`C...`) and can receive USDC directly. A classic `G...` or `M...` recipient needs a USDC trustline first, or the forward fails. Source: [Transfer USDC to and from Stellar](https://developers.circle.com/cctp/quickstarts/transfer-usdc-stellar-arc). **Atomic and non-custodial.** `mint_and_forward` validates the message, mints to the forwarder and pays the recipient in one invocation. Any failure reverts the whole call, and Circle does not hold the funds in between. Source: [How it works](https://developers.circle.com/cctp/references/stellar#how-it-works). **Fast Transfer and forwarding.** Fast Transfer is not applicable when **Stellar is the source**, because Stellar's standard attestation already takes seconds. With Base as the source, Fast Transfer is available for a fee. Circle's Forwarding Service does not cover Stellar as a destination, so you always submit `mint_and_forward` yourself. Source: [Supported chains and domains](https://developers.circle.com/cctp/concepts/supported-chains-and-domains). **Timing.** Most of the wait is on the source side. A Standard Transfer from Base waits for Ethereum finality of the Base batch, which Circle lists at roughly 15 to 19 minutes; a Fast Transfer from Base attests in seconds. The Stellar side is one Soroban transaction. Source: [Finality and block confirmations](https://developers.circle.com/cctp/concepts/finality-and-block-confirmations). **Null fields in Iris.** For messages that involve Stellar, Iris returns the address fields of `decodedMessage` as `null`, because it cannot tell an account from a contract. Read the raw `message` hex if you need them. `amount` and `feeExecuted` are still decoded. Source: [Null address fields](https://developers.circle.com/cctp/references/stellar#null-address-fields-in-api-responses). **Balances are not on Horizon.** A contract wallet's USDC balance lives in the token contract. Read it by simulating `balance(C...)` on the USDC contract over Soroban RPC, as `getStellarDepositBalance` does. ## Troubleshooting | Symptom | Likely cause | What to do | | - | - | - | | Iris keeps returning 404 or `pending_confirmations` | Standard Transfer still waiting for Base finality, or wrong source domain in the URL | Wait up to the finality window; the path is `/v2/messages/6` for Base, not `/27` | | Iris answers 429 | More than 40 requests per second | Poll every few seconds; Circle blocks the client for a few minutes after a 429 | | `mint_and_forward` simulation fails | Message already received, wrong network (mainnet message on testnet forwarder or the reverse), or malformed hook data | Check the burn's network matches the forwarder's, and rebuild the hook data with the helper above | | Burn succeeded, funds never arrive | `mintRecipient` or `destinationCaller` was not `CctpForwarder` | Unrecoverable per Circle. Validate both before every burn, and test the full path on testnet first | | Wallet balance reads `0` after the mint | Reading Horizon, or reading the wrong token contract | Simulate `balance` on the USDC contract `CCW67...MI75` with the wallet's `C...` address | | Vault deposit fails with an amount error | Amount passed with 6 decimals | Multiply by 10, or read the balance as in step 6 | | Received less than burned | Fast Transfer fee deducted at mint | Expected; check `feeExecuted` in the Iris response, or use a Standard Transfer | | `approve` or burn stuck in `awaiting-approval` | Approval message signed incorrectly | EVM messages are hex bytes: sign `ethers.getBytes(message)`. See the gotchas in the [reference repository](https://github.com/defindex-io/crossmint-defindex-guide/blob/main/docs/08-gotchas.md) | ## Resources * [CCTP on Stellar](https://developers.circle.com/cctp/references/stellar), Circle * [CCTP Stellar contracts and interfaces](https://developers.circle.com/cctp/references/stellar-contracts), Circle * [Transfer USDC to and from Stellar](https://developers.circle.com/cctp/quickstarts/transfer-usdc-stellar-arc), Circle quickstart * [Custom EVM transactions](https://docs.crossmint.com/wallets/guides/send-transaction-evm) and [custom Stellar transactions](https://docs.crossmint.com/wallets/guides/send-transaction-stellar), Crossmint * [`defindex-io/crossmint-defindex-guide`](https://github.com/defindex-io/crossmint-defindex-guide), the reference code for the Crossmint wallets and the vault calls # Factory Methods Source: https://docs.defindex.io/advanced-documentation/direct-contract-calls/factory-methods Deploying a vault by calling the factory contract yourself, for a deployment script or `stellar-cli`. To deploy through the API instead, see [Create a Vault](/integration-guide/creating-a-defindex-vault/index). Factory addresses are on [Contract Deployments](/contract-deployments/index). ## Vault Role IDs When calling the factory contract directly, roles are passed as a `Map`. The role IDs are: | ID | Role | Description | | - | - | - | | `0` | Emergency Manager | Can pause strategies and rescue funds in emergencies | | `1` | Fee Receiver | Receives vault performance fees | | `2` | Manager | Full administrative control over the vault | | `3` | Rebalance Manager | Can rebalance asset allocations across strategies | All four roles must be assigned. The same address can be used for multiple roles. *** ## Function: `create_defindex_vault` ```rust theme={null} fn create_defindex_vault( e: Env, roles: Map, vault_fee: u32, assets: Vec, soroswap_router: Address, name_symbol: Map, upgradable: bool, ) -> Result ``` ### Parameter Reference | Parameter | Type | Description | | - | - | - | | `roles` | `Map` | Maps role IDs (0–3) to Stellar addresses. All four roles are required. | | `vault_fee` | `u32` | Vault fee in basis points (1 bps = 0.01%). Range: 0 to 9,000. Above 9,000 the vault panics with `MaximumFeeExceeded`, error 106. | | `assets` | `Vec` | The assets the vault manages and their associated strategies. | | `soroswap_router` | `Address` | Address of the Soroswap router used for internal swaps. | | `name_symbol` | `Map` | Metadata: must contain keys `"name"` and `"symbol"`. | | `upgradable` | `bool` | If `true`, the Manager can upgrade the vault's WASM without user signatures. | ### `AssetStrategySet` Structure ```rust theme={null} struct AssetStrategySet { address: Address, // The token contract address (e.g., USDC or XLM SAC) strategies: Vec, // Strategies that manage this asset } struct Strategy { address: Address, // Strategy contract address name: String, // Human-readable name (stored on-chain) paused: bool, // Set to false on creation; strategies start active } ``` ### Example: `stellar-cli` (Testnet, USDC vault) ```bash theme={null} stellar contract invoke \ --rpc-url https://soroban-testnet.stellar.org \ --network-passphrase 'Test SDF Network ; September 2015' \ --id CDSCWE4GLNBYYTES2OCYDFQA2LLY4RBIAX6ZI32VSUXD7GO6HRPO4A32 \ --source-account deployer \ -- \ create_defindex_vault \ --roles '{"0":"GCKFBEIY...","1":"GCKFBEIY...","2":"GCKFBEIY...","3":"GCKFBEIY..."}' \ --vault_fee 100 \ --assets '[{"address":"CAQCFVLOBK5GIULPNZRGATJJMIZL5BSP7X5YJVMGCPTUEPFM4AVSRCJU","strategies":[{"address":"CALLOM5I7XLQPPOPQMYAHUWW4N7O3JKT42KQ4ASEEVBXDJQNJOALFSUY","name":"BlendUSDC Strategy","paused":false}]}]' \ --soroswap_router CCJUD55AG6W5HAI5LRVNKAE5WDP5XGZBUDS5WNTIVDU7O264UZZE7BRD \ --name_symbol '{"name":"My USDC Vault","symbol":"MUSDC"}' \ --upgradable true ``` > Replace `GCKFBEIY...` with your actual Stellar addresses for each role. ## Function: `create_defindex_vault_deposit` Creates a vault **and** makes the initial deposit in one transaction. ```rust theme={null} fn create_defindex_vault_deposit( e: Env, caller: Address, roles: Map, vault_fee: u32, assets: Vec, soroswap_router: Address, name_symbol: Map, upgradable: bool, amounts: Vec, ) -> Result ``` Additional parameter over `create_defindex_vault`: | Parameter | Type | Description | | - | - | - | | `caller` | `Address` | The address that signs the transaction and makes the deposit. | | `amounts` | `Vec` | Initial deposit amounts in stroops, one per asset in the same order as `assets`. Minimum 1001 per asset. | # Direct Contract Calls Source: https://docs.defindex.io/advanced-documentation/direct-contract-calls/index Calling the vault and factory contracts yourself, without the API in between. Most integrations should use the [Integration Guide](/integration-guide/quickstart) instead: the API builds the transactions for you and you sign and submit them. Come here when you need blockchain interaction with no backend dependency, or control the API does not expose. * [Vault Methods](/advanced-documentation/direct-contract-calls/vault-methods): deposit, withdraw, balance * [Vault Administration](/advanced-documentation/direct-contract-calls/vault-administration): rebalance, rescue, pause, upgrade * [Factory Methods](/advanced-documentation/direct-contract-calls/factory-methods): deploying a vault Addresses are on [Contract Deployments](/contract-deployments/index). The full method list is in the [vault interface](https://github.com/defindex-io/stellar-contracts/blob/main/vault/src/interface.rs). # Vault Administration Source: https://docs.defindex.io/advanced-documentation/direct-contract-calls/vault-administration Methods for whoever operates the vault, rather than for its depositors. ## Rebalance To adjust asset allocation within the vault, use the `rebalance` method. Here are the steps to create the transaction: 1. **Prepare parameters**: * `caller`: The address of the user performing the rebalance. 2. **Example transaction**: ```json theme={null} { "method": "rebalance", "params": { "caller": "GCINP..." } } ``` *** ## Rescue To recover assets in critical situations, use the `rescue` method. Here are the steps to create the transaction: 1. **Prepare parameters**: * `strategy_address`: The address of the strategy from which you want to recover assets. This must be a valid address of a strategy linked to the vault. * `caller`: The address of the user performing the rescue operation. 2. **Example transaction**: ```json theme={null} { "method": "rescue", "params": { "strategy_address": "GCINP...", "caller": "GCINP..." } } ``` *** ## Pause / Unpause To pause or unpause a strategy, use the `pause_strategy` and `unpause_strategy` methods. Here are the steps to create the transactions: 1. **Prepare parameters**: * `strategy_address`: The address of the strategy you want to pause or unpause. * `caller`: The address of the user performing the operation. 2. **Example transaction for pausing**: ```json theme={null} { "method": "pause_strategy", "params": { "strategy_address": "GCINP...", "caller": "GCINP..." } } ``` 3. **Example transaction for unpausing**: ```json theme={null} { "method": "unpause_strategy", "params": { "strategy_address": "GCINP...", "caller": "GCINP..." } } ``` *** ## Upgrade To update the vault's WASM code, use the `upgrade` method. Here are the steps to create the transaction: 1. **Prepare parameters**: * `new_wasm_hash`: The hash of the new WASM code. * `caller`: The address of the user performing the upgrade. 2. **Example transaction**: ```json theme={null} { "method": "upgrade", "params": { "new_wasm_hash": "HASH...", "caller": "GCINP..." } } ``` ## Methods by role Anyone with the right role can call these. See [Vault Roles](/integration-guide/vault-roles) for who holds what. **Management**: `rebalance`, `rescue`, `set_fees`, `pause_strategy` / `unpause_strategy`. **Manager only**: `set_fee_receiver`, `set_manager`, `set_emergency_manager`, `set_rebalance_manager`, `upgrade`, `lock_fees`, `release_fees`. The complete list with parameters is in the [vault interface](https://github.com/defindex-io/stellar-contracts/blob/main/vault/src/interface.rs). # Vault Methods Source: https://docs.defindex.io/advanced-documentation/direct-contract-calls/vault-methods The three user-facing methods on a vault. For the API equivalents, see [Vault Operations](/integration-guide/vault-operations/index). ## Deposit ```rust theme={null} fn deposit( e: Env, amounts_desired: Vec, amounts_min: Vec, from: Address, invest: bool, ) -> Result<(Vec, i128, Option>>), ContractError> ``` * **`amounts_desired`**: the quantity of each asset to deposit. * **`amounts_min`**: the minimum quantity of each asset to transfer, your slippage protection. * **`from`**: the Soroban address making the deposit. * **`invest`**: `true` to invest into the vault's strategies immediately, `false` to leave the funds idle. With `true` the deposit is split in the same proportion as the funds already invested; on a vault with nothing invested yet (`invested_amount` is `0`) the deposit stays idle until the manager runs one `Invest` [rebalance](/advanced-documentation/direct-contract-calls/vault-administration#rebalance). See [Troubleshooting](/integration-guide/troubleshooting#deposit-with-invest-true-stays-idle). ```rust theme={null} let deposit_args = vec![ e, &amounts_desired, &amounts_min, &user_address, &auto_invest, ] let result = e.try_invoke_contract::( &vault_address, &Symbol::new(&e, "deposit"), deposit_args.into_val(e), ).unwrap_or_else(|_| { panic_with_error!(e, SomeError::SomeError); }).unwrap(); ``` Returns the amounts actually deposited, the shares minted, and, when `invest` is `true`, how the funds were allocated across strategies. ## Withdraw * **`withdraw_shares`**: the amount of vault shares to burn. * **`min_amounts_out`**: the minimum amounts to receive before the transaction fails, in underlying assets. * **`from`**: the address performing the withdrawal, which receives the funds. ```json theme={null} { "method": "withdraw", "params": { "withdraw_shares": 500, "min_amounts_out": [450], "from": "GCINP..." } } ``` ```rust theme={null} let withdraw_args = vec![ e, &withdraw_shares, &min_amounts_out, &from ] let result = e.try_invoke_contract::( &vault_address, &Symbol::new(&e, "withdraw"), withdraw_args.into_val(e), ).unwrap_or_else(|_| { panic_with_error!(e, SomeError::SomeError); }).unwrap(); ``` To withdraw a given amount of the underlying asset rather than a number of shares, convert first: call `total_supply` for the vault's total shares and `fetch_total_managed_funds` for the `total_amount` of the asset, then `shares_to_withdraw = total_supply * amount_to_withdraw / total_amount` A vault can hold several assets, so on a single-asset vault take the first element to get its `total_amount`. ## Balance * **`from`**: the Soroban address whose balance you are querying. ```json theme={null} { "method": "balance", "params": { "from": "GCINP..." } } ``` # FAQ Source: https://docs.defindex.io/advanced-documentation/faq Short answers, with the page that has the long one. ### What is DeFindex? Yield infrastructure for neobanks, fintechs and wallets. See [What is DeFindex](/intro/what-is-defindex). ### How does it work? Your users deposit into a vault. The vault spreads that money across strategies, and each strategy connects to one external yield source. Your app reads back one balance and one APY. See [Vaults](/products/vaults). ### How does a partner make money? By setting a fee on the yield the vault generates. See [Fees and revenue](/intro/fees). ### Is it secure? The contracts are open source and audited, and the guarantees are enforced in the contract: a vault can only invest in the strategies fixed at its creation, funds cannot be sent to an outside address, and no role can freeze a withdrawal. See [Risks and Audits](/advanced-documentation/risks-and-audits). ### Is there a lock-up? No. A user withdraws when they want to, with no minimum holding period, no cooldown and no notice. The only requirement is their own signature. See [Vaults](/products/vaults). ### Can a vault's strategies be changed after it is created? No vault function adds or swaps one. Whether the list can change at all is decided when the vault is created: a vault deployed as permanent keeps that list forever, and a vault deployed as upgradable lets its Manager replace the vault's code, which is the only path that can change it. See [Vaults](/products/vaults). ### What do my users actually hold? Shares in the vault, as a token called a dfToken, in their own address. See [Vault Operations](/integration-guide/vault-operations/index). ### Which chains does it run on? Stellar today. The architecture does not depend on it, so ask us where the roadmap is if that matters to you. # Risks and Audits Source: https://docs.defindex.io/advanced-documentation/risks-and-audits ## Risks ### Smart Contracts DeFindex is built on smart contracts. In the event of a hack, funds could be at risk. ### Underlying Protocols Because DeFindex integrates with external DeFi protocols, vulnerabilities in those protocols may affect vault performance. ### Risk Mitigation DeFindex minimizes risk through safeguards enforced at the smart contract level: * **Whitelisted strategies only.** Each vault's strategies are defined when the vault is created. Deposits can only be invested into these whitelisted strategies, and no vault function adds or swaps a strategy afterwards. The one path that can change them is a contract upgrade: a vault deployed as upgradable lets its Manager replace the vault's code entirely, while a vault deployed with upgradability disabled makes the strategy list permanent. * **Funds never leave the vault's ecosystem.** Rebalancing can only move funds between the vault and its whitelisted strategies: unwound funds are hard-coded to return to the vault, and no role can make the vault transfer assets to an arbitrary address. * **Rescue function.** Vault Managers and Emergency Managers can trigger a **rescue function**, which safely unwinds all funds from an underlying strategy back to the vault, where only users can withdraw. This enables proactive risk management in collaboration with chain analysis tools. * **Strategy pausing.** Managers and Emergency Managers can pause a strategy, blocking new investments into it while user withdrawals remain fully available. * **Withdrawals are always open.** No role can freeze user deposits or withdrawals: users can always exit with their share of the vault. * **Fees on yield.** Fees accrue on positive gains. * **First-deposit protection.** Vaults enforce a minimum liquidity of locked "dead shares" on the first deposit, protecting depositors against share-inflation attacks. You can verify these mechanisms directly in the open-source contracts: [defindex-io/stellar-contracts](https://github.com/defindex-io/stellar-contracts). ## Custody DeFindex is non custodial, and no vault role can withdraw a user's deposit or freeze a withdrawal. ## Audits | Auditor | Scope | Date | Report | | - | - | - | - | | [OtterSec](https://osec.io/audits) | DeFindex Vault DeFindex Factory Blend Autocompound Strategy | 2025-03 | [DeFindex Security Assessment](https://github.com/defindex-io/stellar-contracts/blob/main/docs/audits/2025_03_18_ottersec_defindex_audit.pdf) | | [Runtime Verification](https://runtimeverification.com/audits) | Stable APY FeeProxy Boost BoostTreasury | 2026-07 | [DeFindex APY Stabilizer Audit Report](https://github.com/runtimeverification/publications/blob/main/reports/smart-contracts/DeFindex%20APY%20Stabilizer-Audit%20Report-Final.pdf) | | [Halborn](https://www.halborn.com/audits) | Kinetic Autocompound Strategy RWA Wrapper Strategy | 2026-09 | [Smart Contract Assessment](https://github.com/defindex-io/stellar-contracts/blob/main/docs/audits/2026_09_07_halborn_stellar_strategies_audit.pdf) | ### Underlying Protocol Audits DeFindex uses underlying protocols. These protocols have been independently audited: | Protocol | Number of Audits | Audits | | - | - | - | | Blend V2 | 3 | [View audits](https://docs.blend.capital/audits-and-bug-bounties#v2-audits) | | K2 | 3 | [View audits](https://docs.k2lend.com/security-and-audits) | | Precept | 5 | [View audits](https://docs.precept.templarfi.org/security.html) | # Understanding APY Source: https://docs.defindex.io/advanced-documentation/understanding-apy ## What is APY in DeFindex? **APY (Annual Percentage Yield)** represents the estimated annual return on your investment, expressed as a percentage. In DeFindex, APY reflects how much your deposited assets could grow over a year if current performance continues. ### APY vs APR: The Key Difference * **APR (Annual Percentage Rate)**: Simple interest without compounding. If you earn 10% APR, you get exactly 10% on your initial deposit after one year. * **APY (Annual Percentage Yield)**: Includes compound interest. Your earnings are reinvested, so you earn returns on your returns. DeFindex uses APY because it better reflects actual returns when strategies auto-compound rewards. When a vault harvests and reinvests gains, your shares become worth more over time. APY captures this growth more accurately. ### Strategy APY vs Vault APY * **Strategy APY**: The raw yield generated by an individual strategy (e.g., lending on Blend Capital). * **Vault APY**: The net yield users receive after vault fees are deducted. This is what depositors actually earn. A vault with a 10% strategy APY and a 20% fee on yield has approximately 8% vault APY, because the fee applies to the yield the strategy produced. The formula is: `Net Vault APY = Strategy APY × (1 - fee on yield)` For the fee model itself, what your users see and how the money reaches you, see [Fees and revenue](/intro/fees). ### Price Per Share (PPS) Instead of tracking individual profits, DeFindex uses **Price Per Share (PPS)** to measure vault performance. When you deposit, you receive shares. As the vault earns yield, each share becomes worth more. APY is calculated by comparing the PPS now versus the PPS in the past. For technical details and formulas, see [Strategies APY](/strategies/build#strategies-apy). *** ## Why Does APY Vary Between Vaults? Even vaults using similar strategies can show different APYs. Here's why: ### 1. Vault fees The Manager sets the fee on yield, and a lower fee leaves more for depositors. A vault at 15% strategy APY nets about 7.5% at a 50% fee and about 10.5% at 30%. See [Fees and revenue](/intro/fees). ### 2. Rebalancer Decisions The **Rebalance Manager** allocates funds across strategies. Smart rebalancing can optimize returns: * Moving funds to higher-yielding strategies * Responding to market conditions * Balancing risk and reward Poor rebalancing decisions can reduce overall vault performance. ### 3. Entry Timing APY reflects **historical performance**, not future guarantees. DeFindex calculates APY based on Price Per Share (PPS) changes over a recent time window (typically the last 7 days). This means two vaults with identical configurations created at different times will show different APYs. *** ## How to Interpret APY ### What APY Tells You * Recent vault performance based on PPS growth * Net returns after fees * Compounding effect included ### What APY Doesn't Tell You * Future guaranteed returns * Risk level of underlying strategies * Liquidity conditions *** ## Common Misconceptions ### "APY is a guarantee" APY is an estimate based on past performance. Market conditions, strategy yields, and other factors can change at any time. ### "APY stays constant" APY changes continuously as market conditions and strategy performance evolve. What you see today may be different tomorrow. ### "I can directly compare APYs across platforms" Different platforms calculate APY differently. Some include fees, some don't. Some use 7-day averages, others use 30-day. Compare within DeFindex for accuracy. *** ## Quick Reference | Term | Definition | | - | - | | **APY** | Annual Percentage Yield: the estimated yearly return including compounding | | **APR** | Annual Percentage Rate: simple interest without compounding | | **Strategy APY** | Raw yield from a strategy, before the vault fee | | **Vault APY** | Net yield after fees; what depositors actually receive | | **PPS** | Price Per Share: measures how much one vault share is worth | | **Harvest** | Process of claiming and reinvesting strategy rewards | *** ## Learn More * [Strategies APY](/strategies/build#strategies-apy) — Technical formulas and PPS calculations * [Get APY](/integration-guide/vault-operations/get-apy) — How to fetch APY programmatically * [Vault Roles](/integration-guide/vault-roles) — Understanding manager, rebalancer, and fee receiver roles # Generate API Key Source: https://docs.defindex.io/api-reference/account/generate-api-key POST /api-keys/generate Generates a new API key for the authenticated user. Only one API key per user is allowed - generating a new one will revoke the previous one. # Get API Keys Source: https://docs.defindex.io/api-reference/account/list-api-keys GET /api-keys Retrieves all API keys for the authenticated user # Authenticate user and obtain JWT tokens Source: https://docs.defindex.io/api-reference/account/login POST /login **System Function**: Authenticates a user with email/password credentials and returns JWT tokens for API access. This endpoint validates user credentials and provides both access and refresh tokens. The access token is used for authenticating API requests, while the refresh token can be used to obtain new access tokens when they expire. # Refresh JWT access token Source: https://docs.defindex.io/api-reference/account/refresh POST /refresh **System Function**: Obtains a new access token using a valid refresh token. This endpoint allows users to refresh their expired access tokens without requiring re-authentication. Users must provide their valid refresh token to receive new access and refresh tokens. # Register a new user account Source: https://docs.defindex.io/api-reference/account/register POST /register **System Function**: Creates a new user account in the DeFindex platform. This endpoint allows new users to register for access to the DeFindex API. Upon successful registration, users receive authentication credentials that enable them to access protected endpoints and manage their DeFi investments. # Revoke API Key Source: https://docs.defindex.io/api-reference/account/revoke-api-key POST /api-keys/{keyId}/revoke Revokes an API key for the authenticated user # Create a new vault Source: https://docs.defindex.io/api-reference/factory/create-vault POST /factory/create-vault **Manager Function - Vault Manager**: Creates a new DeFindex vault with the specified configuration parameters. This endpoint allows authorized vault managers to deploy new vault contracts through the factory. The vault will be configured with the provided assets, strategies, and management parameters. This is typically used during the initial setup phase of a new investment strategy. # Create vault with auto-invest Source: https://docs.defindex.io/api-reference/factory/create-vault-auto-invest POST /factory/create-vault-auto-invest **Advanced Function**: Creates a new DeFindex vault and automatically invests deposited funds. This endpoint creates a batched transaction that: 1. Creates the vault with initial deposit 2. Invests funds in specified strategies (rebalance) 3. Changes manager to the final address All operations are atomic - either all succeed or all fail. This provides a seamless user experience for creating fully-invested vaults in a single transaction. # Create vault and deposit in single transaction Source: https://docs.defindex.io/api-reference/factory/create-vault-deposit POST /factory/create-vault-deposit **User Experience Function**: Creates a new DeFindex vault and performs an initial deposit in a single atomic transaction. This endpoint combines vault creation and initial deposit, providing a streamlined user experience for launching a new vault with immediate funding. This is ideal for users who want to create and immediately invest in a new vault strategy. # Get factory contract address Source: https://docs.defindex.io/api-reference/factory/factory-address GET /factory/address **System Function**: Retrieves the address of the factory contract for a specific Stellar network. This endpoint provides the factory contract address that is used to create new vaults. It's essential for applications that need to interact with the factory contract to deploy new vault instances. # Get an account's flat transaction history in a vault Source: https://docs.defindex.io/api-reference/historical-data/account-events GET /account/{walletAddress}/vault/{vaultAddress}/events Returns a paginated list of deposit, withdraw, transfer_in, and transfer_out events for a given account in a vault, sorted newest-first by ledger. Use for tx-table / activity-log UIs. The performance endpoint (`/account/:wallet/vault/:vault`) is the right place for chart data with per-bucket event annotations. # Get account vault performance metrics Source: https://docs.defindex.io/api-reference/historical-data/account-performance GET /account/{walletAddress}/vault/{vaultAddress} **User Experience Function**: Retrieves comprehensive performance metrics for a specific account's position in a vault including current position value, ROI, APY across different periods (24h, 7d, 30d, since inception), total deposits/withdrawals, interest earned, and historical time series data tracking position value over time. # Daily active users (holders), new and churned, over a period Source: https://docs.defindex.io/api-reference/historical-data/active-users GET /vault/{address}/active-users # Get vault depositor analytics Source: https://docs.defindex.io/api-reference/historical-data/depositors GET /vault/{address}/depositors Returns a paginated list of all depositors with estimated balance, activity status, and transaction history. Status is computed from idleThresholdDays and minBalance thresholds (configurable per-user via VaultUserConfig, overridable by query params). NOTE: v1 only supports single-asset vaults; multi-asset vaults default to assets[0]. # Get vault historical performance metrics Source: https://docs.defindex.io/api-reference/historical-data/vault-history GET /vault/{address}/history **User Experience Function**: Retrieves comprehensive historical performance data for a specific vault including Price Per Share (PPS) history, supply tracking, deposits, withdrawals, gains, fees, and APY metrics across different time periods. The endpoint supports flexible period selection (all, 7d, 30d, 90d, 1y) and data aggregation intervals (hourly, daily, weekly, monthly). # Migrate a full position between two DeFindex vaults Source: https://docs.defindex.io/api-reference/migration/defindex-to-defindex POST /migration/defindex-to-defindex Builds an unsigned, atomic Stellar Router transaction that withdraws the caller's entire share balance from `fromVault` and deposits the proceeds into `toVault`. Both legs live in one transaction, so the migration either fully succeeds or fully reverts. The deposited amount is a floor derived from `slippageBps`; any surplus is left in the caller's wallet. # Submit signed transaction to Stellar blockchain Source: https://docs.defindex.io/api-reference/transactions/send POST /send **System Function**: Submits a pre-signed DeFindex transaction to the Stellar blockchain network. This endpoint allows users to submit transaction XDRs that have been prepared by other DeFindex endpoints and signed by the user. The service handles transaction submission and provides gas-free transaction processing for valid DeFindex operations. # API health check Source: https://docs.defindex.io/api-reference/utilities/health GET /health **System Function**: Performs a comprehensive health check on the DeFindex API. This endpoint provides: - API service availability and connectivity - Database connection status (mainnet and testnet) - Connection pool statistics Useful for monitoring tools, load balancers, and operational dashboards. # Distribute vault fees Source: https://docs.defindex.io/api-reference/vault-management/distribute-fees POST /vault/{address}/distribute-fees **Manager Function**: Distributes the fees accrued by the vault to the designated recipients. This operation is performed by the manager to manage fee distribution effectively. # Get fee status for a vault Source: https://docs.defindex.io/api-reference/vault-management/fee-status GET /vault/{address}/fees/status # Get vault role Source: https://docs.defindex.io/api-reference/vault-management/get-role GET /vault/{address}/get/{role} **User Experience Function**: Unified endpoint for retrieving vault role addresses. **Supported roles:** - **manager**: Retrieves the current manager address - **emergency-manager**: Retrieves the current emergency manager address - **rebalance-manager**: Retrieves the current rebalance manager address - **fee-receiver**: Retrieves the current fee receiver address The role parameter in the URL determines which role address will be retrieved. # Lock vault fees Source: https://docs.defindex.io/api-reference/vault-management/lock-fees POST /vault/{address}/lock-fees **Manager Function**: Locks the fees accrued by the vault, preventing further accrual until the fees are released or distributed. This operation is performed by the manager to manage fee collection and distribution. # Pause a vault strategy Source: https://docs.defindex.io/api-reference/vault-management/pause-strategy POST /vault/{address}/pause-strategy **Manager Function - Strategy Manager**: Temporarily halts operations of a specific strategy within a vault. # Rebalance vault strategies Source: https://docs.defindex.io/api-reference/vault-management/rebalance POST /vault/{address}/rebalance **Manager Function - Rebalance Manager**: Rebalances the strategies within a vault to optimize asset allocation and performance. This operation adjusts the distribution of assets across strategies based on predefined criteria or market conditions. # Release locked vault fees Source: https://docs.defindex.io/api-reference/vault-management/release-fees POST /vault/{address}/release-fees **Manager Function**: Releases the fees that were previously locked by the vault manager. This operation allows the manager to distribute or utilize the locked fees as needed. # Generate strategy reports for vault Source: https://docs.defindex.io/api-reference/vault-management/report GET /vault/{address}/report **User Experience Function**: Generates performance reports for all strategies in the vault, tracking their performance metrics, gains/losses, and fee accrual. This operation updates strategy balances and calculates performance since the last report. # Rescue assets from a strategy Source: https://docs.defindex.io/api-reference/vault-management/rescue POST /vault/{address}/rescue **Manager Function - Emergency Manager**: Emergency operation to rescue assets from a strategy that may be malfunctioning or at risk. # Set vault role Source: https://docs.defindex.io/api-reference/vault-management/set-role POST /vault/{address}/set/{role} **Manager Function**: Unified endpoint for setting vault roles. **Supported roles:** - **manager**: Updates the manager address (requires current Manager role) - **emergency-manager**: Updates the emergency manager address (requires Manager role) - **rebalance-manager**: Updates the rebalance manager address (requires Manager role) - **fee-receiver**: Updates the fee receiver address (requires Manager or current fee receiver role) The role parameter in the URL determines which role will be updated. # Unpause a vault strategy Source: https://docs.defindex.io/api-reference/vault-management/unpause-strategy POST /vault/{address}/unpause-strategy **Manager Function - Strategy Manager**: Resumes operations of a previously paused strategy within a vault. # Upgrade vault contract wasm Source: https://docs.defindex.io/api-reference/vault-management/upgrade POST /vault/{address}/upgrade **Manager Function**: Upgrades the vault contract to a new version by providing the new WASM hash. This operation is performed by the manager to ensure the vault contract is up-to-date with the latest features and fixes. # Get vault 7-day Annual Percentage Yield (APY) Source: https://docs.defindex.io/api-reference/vaults/apy GET /vault/{address}/apy **User Experience Function**: Retrieves the 7-day Annual Percentage Yield (APY) for a vault. This endpoint calculates APY based on the vault's performance over the last 7 days and returns it as an annualized percentage. # Get user vault balance Source: https://docs.defindex.io/api-reference/vaults/balance GET /vault/{address}/balance **User Experience Function**: Retrieves the balance information for a specific user in a vault, including the number of shares owned and their current value in underlying assets. # Deposit assets into vault Source: https://docs.defindex.io/api-reference/vaults/deposit POST /vault/{address}/deposit **User Experience Function**: Allows users to deposit assets into a vault and receive vault shares in return. # Discover main Defindex vaults Source: https://docs.defindex.io/api-reference/vaults/discover GET /vault/discover Queries the factory contract for main Defindex vaults and returns their addresses with total managed funds. Results are cached for 5 minutes. # Get all strategies with TVL and APY Source: https://docs.defindex.io/api-reference/vaults/strategies GET /strategies Returns all registered strategies with their current TVL, APY (7d/30d/all-time), name, underlying asset, and strategy type. # Get vault information Source: https://docs.defindex.io/api-reference/vaults/vault-info GET /vault/{address} **User Experience Function**: Retrieves comprehensive information about a specific vault including metadata, total value locked (TVL), underlying assets, and current strategies. # Withdraw specific asset amounts from vault Source: https://docs.defindex.io/api-reference/vaults/withdraw POST /vault/{address}/withdraw **User Experience Function**: Allows users to withdraw specific amounts of underlying assets from a vault by burning the equivalent vault shares. # Withdraw by burning specific amount of vault shares Source: https://docs.defindex.io/api-reference/vaults/withdraw-shares POST /vault/{address}/withdraw-shares **User Experience Function**: Allows users to withdraw from a vault by specifying the exact number of vault shares to burn. # About Us Source: https://docs.defindex.io/community/about-us **DeFindex** **🔁** is yield infrastructure for neobanks, fintechs and wallets, developed by **PaltaLabs 🥑**, a blockchain studio based in Latin America. It lets a partner integrate automated investment strategies through modular smart contracts, Vaults, Strategies and Factory, that connect DeFi protocols to accessible user interfaces. Our mission is to **democratize access to global financial products**, allowing any financial app to offer yield opportunities with no technical friction, optimized performance, and a seamless user experience. Follow PaltaLabs: [https://x.com/PaltaLabs](https://x.com/PaltaLabs) # Contact the DeFindex team Source: https://docs.defindex.io/community/contact Book a call, or find us on Discord. > [card] [Book a call](https://paltalabs.io/esteban/cal) > > Thirty minutes with the team. Bring your use case. > [card] [Discord](https://discord.gg/aV5jHwmsaj) > > The wallet-and-api channel. Integration questions get answered here. > [card] [X](https://x.com/defindex_) > > Product updates. > [card] [GitHub](https://github.com/defindex-io) > > The contracts, the strategies and the guides. DeFindex is built by [PaltaLabs](https://x.com/PaltaLabs). # Terms of Use Source: https://docs.defindex.io/community/terms-of-use The short version, and a link to the binding one. Your access to and use of DeFindex, including our websites, web applications, APIs, smart contracts and all associated services, is governed by the DeFindex **Terms of Use**. DeFindex develops and operates non-custodial blockchain software infrastructure. It is not a financial institution, custodian, broker, or investment adviser, and never holds or controls your private keys or digital assets. Before interacting with the protocol, please review the full Terms, including the risk disclosures and the arbitration and class-action waiver provisions. > [!NOTE] > > Read the complete and legally binding document here: [**DeFindex Terms of Use**](https://defindex.io/terms). For questions regarding the Terms, contact us at [hello@defindex.io](mailto:hello@defindex.io). # Contract Deployments Source: https://docs.defindex.io/contract-deployments/index Always verify contract addresses before interacting with them. ## Mainnet The same list in JSON: [mainnet.contracts.json](https://github.com/defindex-io/stellar-contracts/blob/main/public/mainnet.contracts.json). ### Core Contracts | Contract | Contract ID | Hash | | - | - | - | | Factory | [`CDKFHFJIET3A73A2YN4KV7NSV32S6YGQMUFH3DNJXLBWL4SKEGVRNFKI`](https://stellar.expert/explorer/public/contract/CDKFHFJIET3A73A2YN4KV7NSV32S6YGQMUFH3DNJXLBWL4SKEGVRNFKI) | `b0fe36b2b294d0af86846ccc4036279418907b60f6f74dae752847ae9d3bca0e` | | Vault | One per vault | `ae3409a4090bc087b86b4e9b444d2b8017ccd97b90b069d44d005ab9f8e1468b` | ### Strategy Contracts #### Blend Autocompound Hash `11329c2469455f5a3815af1383c0cdddb69215b1668a17ef097516cde85da988`. One instance per asset and venue, all running that hash: | Asset | Pool | Contract ID | | - | - | - | | [USDC](https://stellar.expert/explorer/public/contract/CCW67TSZV3SSS2HXMBQ5JFGCKJNXKZM7UQUWUZPUTHXSTZLEO7SJMI75) | [Fixed](https://mainnet.blend.capital/dashboard/?poolId=CAJJZSGMMM3PD7N33TAPHGBUGTB43OC73HVIK2L2G6BNGGGYOSSYBXBD) | [`CDB2WMKQQNVZMEBY7Q7GZ5C7E7IAFSNMZ7GGVD6WKTCEWK7XOIAVZSAP`](https://stellar.expert/explorer/public/contract/CDB2WMKQQNVZMEBY7Q7GZ5C7E7IAFSNMZ7GGVD6WKTCEWK7XOIAVZSAP) | | [EURC](https://stellar.expert/explorer/public/contract/CDTKPWPLOURQA2SGTKTUQOWRCBZEORB4BWBOMJ3D3ZTQQSGE5F6JBQLV) | [Fixed](https://mainnet.blend.capital/dashboard/?poolId=CAJJZSGMMM3PD7N33TAPHGBUGTB43OC73HVIK2L2G6BNGGGYOSSYBXBD) | [`CC5CE6MWISDXT3MLNQ7R3FVILFVFEIH3COWGH45GJKL6BD2ZHF7F7JVI`](https://stellar.expert/explorer/public/contract/CC5CE6MWISDXT3MLNQ7R3FVILFVFEIH3COWGH45GJKL6BD2ZHF7F7JVI) | | [XLM](https://stellar.expert/explorer/public/contract/CAS3J7GYLGXMF6TDJBBYYSE3HQ6BBSMLNUQ34T6TZMYMW2EVH34XOWMA) | [Fixed](https://mainnet.blend.capital/dashboard/?poolId=CAJJZSGMMM3PD7N33TAPHGBUGTB43OC73HVIK2L2G6BNGGGYOSSYBXBD) | [`CDPWNUW7UMCSVO36VAJSQHQECISPJLCVPDASKHRC5SEROAAZDUQ5DG2Z`](https://stellar.expert/explorer/public/contract/CDPWNUW7UMCSVO36VAJSQHQECISPJLCVPDASKHRC5SEROAAZDUQ5DG2Z) | | [USDC](https://stellar.expert/explorer/public/contract/CCW67TSZV3SSS2HXMBQ5JFGCKJNXKZM7UQUWUZPUTHXSTZLEO7SJMI75) | [Etherfuse](https://mainnet.blend.capital/dashboard/?poolId=CDMAVJPFXPADND3YRL4BSM3AKZWCTFMX27GLLXCML3PD62HEQS5FPVAI) | [`CCBTSHPUVNKCT5V675AAVYNANHXBU26PTZK2QLS7ZLFNYRJZT5HW3VL6`](https://stellar.expert/explorer/public/contract/CCBTSHPUVNKCT5V675AAVYNANHXBU26PTZK2QLS7ZLFNYRJZT5HW3VL6) | | [CETES](https://stellar.expert/explorer/public/contract/CAL6ER2TI6CTRAY6BFXWNWA7WTYXUXTQCHUBCIBU5O6KM3HJFG6Z6VXV) | [Etherfuse](https://mainnet.blend.capital/dashboard/?poolId=CDMAVJPFXPADND3YRL4BSM3AKZWCTFMX27GLLXCML3PD62HEQS5FPVAI) | [`CAZ3LLLKPWEOVK6K4G5NCQ2VXWABLFIPKKNMN5GLKMZKEN7JSKTEMIKN`](https://stellar.expert/explorer/public/contract/CAZ3LLLKPWEOVK6K4G5NCQ2VXWABLFIPKKNMN5GLKMZKEN7JSKTEMIKN) | | [USTRY](https://stellar.expert/explorer/public/contract/CBLV4ATSIWU67CFSQU2NVRKINQIKUZ2ODSZBUJTJ43VJVRSBTZYOPNUR) | [Etherfuse](https://mainnet.blend.capital/dashboard/?poolId=CDMAVJPFXPADND3YRL4BSM3AKZWCTFMX27GLLXCML3PD62HEQS5FPVAI) | [`CA3SO5RRKOONAPWVR5XY6CMOYZGN4M4QKVIGX5DFRIIJUJW2SFSELBXL`](https://stellar.expert/explorer/public/contract/CA3SO5RRKOONAPWVR5XY6CMOYZGN4M4QKVIGX5DFRIIJUJW2SFSELBXL) | | [TESOURO](https://stellar.expert/explorer/public/contract/CD6M4R2322BYCY2LNWM74PEBQAQ63SA3DUJLI3L4225U4ZVCLMSCBCIS) | [Etherfuse](https://mainnet.blend.capital/dashboard/?poolId=CDMAVJPFXPADND3YRL4BSM3AKZWCTFMX27GLLXCML3PD62HEQS5FPVAI) | [`CDSCVJHJWUZQMR64FVK3XMND5NKSN7Z23KPRCHKFHVGOEJBWPVH5B5XA`](https://stellar.expert/explorer/public/contract/CDSCVJHJWUZQMR64FVK3XMND5NKSN7Z23KPRCHKFHVGOEJBWPVH5B5XA) | Fixed and Etherfuse are [Blend Capital](https://docs.blend.capital/) pools, linked to their own dashboards. DeFindex does not deploy them. #### RWA Wrapper Hash `9a0680a3c20d20938b5100ff4784dad22d92f566d4b3137945639d2b077aefa3`. One instance per bond token, all running that hash. Each instance takes the underlying asset, holds a value-accruing bond token, and trades between the two on [Aquarius](https://aqua.network/): | Underlying | Bond | Contract ID | | - | - | - | | [USDC](https://stellar.expert/explorer/public/contract/CCW67TSZV3SSS2HXMBQ5JFGCKJNXKZM7UQUWUZPUTHXSTZLEO7SJMI75) | [CETES](https://stellar.expert/explorer/public/contract/CAL6ER2TI6CTRAY6BFXWNWA7WTYXUXTQCHUBCIBU5O6KM3HJFG6Z6VXV) | [`CBYE43TMFQ6ZTGX336I4YOROFU23FKEBHSVY6WM3SAR2HVTLSCURPONU`](https://stellar.expert/explorer/public/contract/CBYE43TMFQ6ZTGX336I4YOROFU23FKEBHSVY6WM3SAR2HVTLSCURPONU) | #### Kinetic Autocompound Hash `163d4c266d66f69b49593cbc23b6381fe8da3d5aa0a9d0c59b45923cab0a5ebd`. One instance per asset, all running that hash. Each instance supplies the asset to [K2](https://app.k2lend.com/), holds the resulting kToken, and lets the keeper harvest rewards, swap them to the asset and re-supply: | Asset | Venue | Contract ID | | - | - | - | | [USDC](https://stellar.expert/explorer/public/contract/CCW67TSZV3SSS2HXMBQ5JFGCKJNXKZM7UQUWUZPUTHXSTZLEO7SJMI75) | [K2](https://app.k2lend.com/) | [`CAOK66QTVE2QXWJPDXDX75ULFKUQDN43AXKYWOBZAERCPZOJL2UEBVJW`](https://stellar.expert/explorer/public/contract/CAOK66QTVE2QXWJPDXDX75ULFKUQDN43AXKYWOBZAERCPZOJL2UEBVJW) | ## Testnet Testnet redeploys often, so the addresses live only in JSON: [testnet.contracts.json](https://github.com/defindex-io/stellar-contracts/blob/main/public/testnet.contracts.json). # Welcome Source: https://docs.defindex.io/index DeFindex is yield infrastructure for neobanks, fintechs and wallets. Integrate once, offer a balance that earns, keep a share of the yield. > [card] [Fees and revenue](/intro/fees) > > How the fee works, and what you keep. > [card] [Why DeFindex](/intro/why-defindex) > > What you get, compared with building it yourself. > [card] [Quickstart](/integration-guide/quickstart) > > From zero to a confirmed deposit in three steps. > [card] [Open the Console](https://console.defindex.io) > > Create a vault, set your fee and get your API key with no code. # Create a Vault Source: https://docs.defindex.io/integration-guide/creating-a-defindex-vault/index DeFindex Vaults let **wallet builders** design yield products tailored to their users.\ With a vault, you choose the **assets**, **strategies**, **allocation**, and **fees**—and you can rebalance positions or rescue funds at any time. From the end-user's perspective, it's just **deposit and withdraw**. *** ## Vault Creation Requirements Before you deploy a vault, make sure you meet the following requirements. These details are often the source of confusion for new builders. ### Network DeFindex operates on **Stellar Mainnet** and **Stellar Testnet**. The two networks are completely independent and use different contract addresses and token types. | Requirement | Testnet | Mainnet | | - | - | - | | Network Passphrase | `Test SDF Network ; September 2015` | `Public Global Stellar Network ; September 2015` | | Factory contract | See [Contract Deployments](/contract-deployments/index) | See [Contract Deployments](/contract-deployments/index) | | RPC URL | `https://soroban-testnet.stellar.org` | `https://soroban.stellar.org` or another provider | | Horizon URL | `https://horizon-testnet.stellar.org` | `https://horizon.stellar.org` | ### Tokens **On Testnet**, DeFindex strategies use a test USDC issued by the Blend Capital testnet deployment — referred to here as **BlendUSDC**. This is **not** Soroswap or regular USDC; it is a separate test token you must obtain from [testnet.blend.capital](https://testnet.blend.capital). **On Mainnet**, strategies use real USDC (Circle) and other well-known tokens. #### Token addresses | Token | Network | Contract Address | | - | - | - | | XLM (native SAC) | Testnet & Mainnet | `CDLZFC3SYJYDZT7K67VZ75HPJVIEUVNIXF47ZG2FB2RMQQVU2HHGCYSC` | | BlendUSDC | **Testnet only** | `CAQCFVLOBK5GIULPNZRGATJJMIZL5BSP7X5YJVMGCPTUEPFM4AVSRCJU` | | USDC (Circle) | **Mainnet only** | `CCW67TSZV3SSS2HXMBQ5JFGCKJNXKZM7UQUWUZPUTHXSTZLEO7SJMI75` | | CETES | Testnet | `CC72F57YTPX76HAA64JQOEGHQAPSADQWSY5DWVBR66JINPFDLNCQYHIC` | For a full list of deployed strategy contract addresses, see the [Contract Deployments](/contract-deployments/index) section. ### Getting Testnet Tokens You need testnet tokens to deploy and interact with a vault on testnet: 1. **XLM (for fees)**: Use [Friendbot](https://friendbot.stellar.org/) to fund your testnet account. ``` https://friendbot.stellar.org/?addr=YOUR_STELLAR_ADDRESS ``` 2. **BlendUSDC** (required for USDC vaults on testnet): * Go to [testnet.blend.capital](https://testnet.blend.capital). * Connect your Freighter wallet (switch to Testnet in wallet settings first). * Click **"Faucet"** or use the asset menu to add a BlendUSDC trustline and receive test tokens. 3. **CETES** (required for CETES vaults on testnet): * Same place as BlendUSDC: on [testnet.blend.capital](https://testnet.blend.capital), add a trustline for the test CETES token and use the faucet. It is a test token in a Blend testnet pool, not issued by Etherfuse. > **Why BlendUSDC?** On testnet, DeFindex strategies are deployed against the Blend Capital testnet pools, which use their own test USDC. Real Circle USDC does not support large amounts minting on Stellar Testnet. ### Funding Requirements A **minimum first deposit of 1001 units** (in the asset's smallest denomination — stroops) of your vault's underlying asset is required immediately after deployment. * On the **first deposit**, the vault locks **1000 shares** as an inflation-attack defense mechanism. * **Example**: For a USDC vault (7 decimals), 1001 stroops = **0.0001001 USDC** — practically free. * **Example**: For an XLM vault (7 decimals), 1001 stroops = **0.0001001 XLM** — also negligible. This is required to prevent the [ERC-4626 inflation attack](https://blog.openzeppelin.com/a-novel-defense-against-erc4626-inflation-attacks) (the same class of attack applies to Soroban vaults). > A new vault does **not** invest its first deposit, even with `invest: true`: the flag follows the vault's current allocation, and a new vault has none. After the first deposit you must perform a [**first rebalance**](/integration-guide/creating-a-defindex-vault/index#step-5-first-rebalance) to allocate funds across strategies. From then on, deposits with `invest: true` are invested automatically. > [!NOTE] > > A first deposit of 20 USDC prevents historical APY endpoint from having approximation errors *** ### Step 1: Assign Vault Roles, Fees, and Upgradability Before deployment, you must configure the following **roles** (each tied to an address): * **Manager** – primary owner, manages settings, upgrades, and other roles (use a secure wallet, ex. multisig, cold or MPC) * **Emergency Manager** – rescues funds and pauses risky strategies (use a hot wallet with fast access or automate it for faster response) * **Rebalance Manager** – allocates funds across strategies (use a hot wallet or it can be managed by a third party) * **Fee Receiver** – collects performance fees (*use a secure, dedicated wallet*) > All four roles must be assigned. You may use the same address for multiple roles, but this is not recommended for production. *** **Fees** * Fees are expressed in **basis points** (1 bp = 0.01%). * The **Vault Fee** is applied to strategy earnings and assigned to the Fee Receiver. * Maximum allowed fee: **9,000 bps (90% of yield)**. The vault contract rejects any value above 9,000 with `MaximumFeeExceeded` (error 106). *** **Upgradability** * Choose whether this vault can be upgraded after deployment. * If enabled, you can migrate to a new vault version in the future. * Your users' funds and positions remain unaffected — no action required on their end. *** ### Step 2: Select Assets and Strategies DeFindex offers **curated and audited strategies**, currently live for: * **Blend Autocompound – Fixed Pool**: USDC, EURC, XLM * **Blend Autocompound – Etherfuse Pool**: USDC, CETES, USTRY, TESOURO Each vault supports one or more assets, and each asset can be backed by one or more strategies. > Need support for additional pools? Just ping us on [Discord](https://discord.gg/aV5jHwmsaj). *** ### Step 3: Deploy the Vault You can deploy your Vault in two ways: * [**Using the Console**](/integration-guide/creating-a-defindex-vault/using-the-console) **(no code — skip the next steps if you use it)** * [**Using the API (Advanced)**](/integration-guide/creating-a-defindex-vault/using-the-api) > [card] [Create your vault in the Console](https://console.defindex.io) > > The guided flow at console.defindex.io deploys the vault and then manages it: deposits, rebalancing, fees, and roles in one place. ### Step 4: Do a First Deposit (the Console does it when **Deposit on creation** is on) A **minimum first deposit of 1001 units** of your supported asset is required. * **Why?** * **1001 units** will be permanently locked in the Vault for security. * **Example:**\ If you are depositing **USDC**, this equals just **0.0001001 USDC** — practically nothing! This is because these vaults are protected from something called "inflation attacks" you can read more about this kind of attacks on [OpenZeppelin blog](https://blog.openzeppelin.com/a-novel-defense-against-erc4626-inflation-attacks) ### Step 5: First Rebalance (the Console does it when **Auto-invest deposited funds** is on) After deployment, perform the **first rebalance** to define allocations across chosen strategies. This may be a bit confusing right? but How the vault is going to know how to distribute the funds across the different strategies? This step only need to be done once. > [!WARNING] > > If you skip this step, every deposit stays idle, including deposits with `invest: true`. The vault has no allocation to follow yet. Vaults created from the Console with **Deposit on creation** or **Auto-invest deposited funds** turned off are in this state too: run the Invest from the vault's **Admin** tab. See [Deposit with `invest: true` stays idle](/integration-guide/troubleshooting#deposit-with-invest-true-stays-idle). You have two ways to make the first rebalance: using the API, or using [stellar-cli](https://developers.stellar.org/docs/build/guides/cli). #### Using API Make sure you have an `API_KEY` to call the API. And then, call the rebalance function ``` curl --location 'https://api.defindex.io/vault/${VAULT_ADDRESS}/rebalance?network=mainnet' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer ${JWT_TOKEN}' \ --data '{ "caller": "${MANAGER_OR_REBALANCE_MANAGER}$", "instructions": [ { "type": "Invest", "strategy_address": "${STRATEGY_ADDRESS}$", "amount": 1000000 } ] }' ``` Where `VAULT_ADDRESS` is the address of the recently deployed vault, `JWT_TOKEN` is the API key, the `MANAGER_OR_REBALANCE_MANAGER` is what you defined when creating the vault. The strategy address is the one you want to invest on. For a list of all the addresses you can check -> [here](https://github.com/defindex-io/stellar-contracts/blob/main/public/mainnet.contracts.json). This will return you an unsigned XDR, that can be signed using your preferred method of signing. One simple method could be using [Stellar Laboratory](https://lab.stellar.org/transaction/sign). Simply copy and paste the unsigned XDR and sign it. #### Using stellar-cli First, you need to setup your keys, make sure the rebalancer manager role defined previously is the one you are going to setup. For example, you can set it up using secret key by: ```bash theme={null} stellar keys add --secret-key rebalancer ``` then, you will be prompted to write your secret key. Next, let's make the rebalance using testnet as example. You can do that by: ```bash theme={null} stellar contract invoke \ --rpc-url https://soroban-testnet.stellar.org/ \ --network-passphrase 'Test SDF Network ; September 2015' \ --id \ --source-account rebalancer \ -- \ rebalance \ --caller \ --instructions '[{"Invest":["", ""]}]' ``` you can find the strategy addresses on [`~/public/.contracts.json`](https://github.com/defindex-io/stellar-contracts/blob/main/public/mainnet.contracts.json). And that's all! # Using the API Source: https://docs.defindex.io/integration-guide/creating-a-defindex-vault/using-the-api This guide documents every argument involved in deploying a DeFindex vault — whether you call the factory smart contract directly or use the DeFindex REST API. Read the [Vault Creation Requirements](/integration-guide/creating-a-defindex-vault/index#vault-creation-requirements) section first before proceeding. *** ## Quick Reference: Contract Addresses ### Testnet Stellar wipes the testnet periodically, and these addresses stop working when it does. The next scheduled reset is December 16, 2026. If an address no longer works, let us know via Discord so we can update the docs. | Contract | Address | | - | - | | Factory | `CDSCWE4GLNBYYTES2OCYDFQA2LLY4RBIAX6ZI32VSUXD7GO6HRPO4A32` | | Soroswap Router | `CCJUD55AG6W5HAI5LRVNKAE5WDP5XGZBUDS5WNTIVDU7O264UZZE7BRD` | | XLM (native SAC) | `CDLZFC3SYJYDZT7K67VZ75HPJVIEUVNIXF47ZG2FB2RMQQVU2HHGCYSC` | | BlendUSDC | `CAQCFVLOBK5GIULPNZRGATJJMIZL5BSP7X5YJVMGCPTUEPFM4AVSRCJU` | | CETES token | `CC72F57YTPX76HAA64JQOEGHQAPSADQWSY5DWVBR66JINPFDLNCQYHIC` | | USDC Blend Strategy | `CALLOM5I7XLQPPOPQMYAHUWW4N7O3JKT42KQ4ASEEVBXDJQNJOALFSUY` | | XLM Blend Strategy | `CDVLOSPJPQOTB6ZCWO5VSGTOLGMKTXSFWYTUP572GTPNOWX4F76X3HPM` | | CETES Blend Strategy | `CCP4RBDWPRNO2LWO23XFU4BBLGA73J5N3BK7EHRJUHVN33YEMMFB2MBE` | ### Mainnet | Contract | Address | | - | - | | Factory | `CDKFHFJIET3A73A2YN4KV7NSV32S6YGQMUFH3DNJXLBWL4SKEGVRNFKI` | | Soroswap Router | `CAG5LRYQ5JVEUI5TEID72EYOVX44TTUJT5BQR2J6J77FH65PCCFAJDDH` | | XLM (native SAC) | `CDLZFC3SYJYDZT7K67VZ75HPJVIEUVNIXF47ZG2FB2RMQQVU2HHGCYSC` | | USDC (Circle) | `CCW67TSZV3SSS2HXMBQ5JFGCKJNXKZM7UQUWUZPUTHXSTZLEO7SJMI75` | | USDC Fixed Pool Strategy | `CDB2WMKQQNVZMEBY7Q7GZ5C7E7IAFSNMZ7GGVD6WKTCEWK7XOIAVZSAP` | | EURC Fixed Pool Strategy | `CC5CE6MWISDXT3MLNQ7R3FVILFVFEIH3COWGH45GJKL6BD2ZHF7F7JVI` | | XLM Fixed Pool Strategy | `CDPWNUW7UMCSVO36VAJSQHQECISPJLCVPDASKHRC5SEROAAZDUQ5DG2Z` | For the complete list of mainnet strategies, see [Contract Deployments](/contract-deployments/index). *** ## `POST /factory/create-vault` Builds an unsigned XDR to deploy a vault. You must sign the XDR and submit it via `POST /send`. ```http theme={null} POST https://api.defindex.io/factory/create-vault?network=testnet Authorization: Bearer Content-Type: application/json ``` ### Request Body ```json theme={null} { "roles": { "manager": "GACKTN5D...", "emergencyManager": "GACKTN5D...", "rebalanceManager": "GACKTN5D...", "feeReceiver": "GACKTN5D..." }, "vaultFeeBps": 100, "assets": [ { "address": "CAQCFVLOBK5GIULPNZRGATJJMIZL5BSP7X5YJVMGCPTUEPFM4AVSRCJU", "strategies": [ { "address": "CALLOM5I7XLQPPOPQMYAHUWW4N7O3JKT42KQ4ASEEVBXDJQNJOALFSUY", "name": "BlendUSDC Strategy", "paused": false } ] } ], "name": "My USDC Vault", "symbol": "MUSDC", "upgradable": true, "caller": "GACKTN5D..." } ``` ### Field Reference | Field | Type | Required | Description | | - | - | - | - | | `roles.manager` | `string` | Yes | Stellar address for the Manager role | | `roles.emergencyManager` | `string` | Yes | Stellar address for the Emergency Manager role | | `roles.rebalanceManager` | `string` | Yes | Stellar address for the Rebalance Manager role | | `roles.feeReceiver` | `string` | Yes | Stellar address for the Fee Receiver role | | `vaultFeeBps` | `number` | Yes | Vault fee in basis points (0–9000). `100` = 1% | | `assets` | `Asset[]` | Yes | Array of assets the vault will manage | | `assets[].address` | `string` | Yes | Token contract address for this asset | | `assets[].strategies` | `Strategy[]` | Yes | Strategies that manage this asset | | `assets[].strategies[].address` | `string` | Yes | Strategy contract address | | `assets[].strategies[].name` | `string` | Yes | Human-readable name stored on-chain | | `assets[].strategies[].paused` | `boolean` | Yes | Whether the strategy starts paused. Use `false` | | `name` | `string` | Yes | Vault display name (stored on-chain) | | `symbol` | `string` | Yes | Vault token symbol for dfTokens (e.g., `MUSDC`) | | `upgradable` | `boolean` | Yes | Whether the vault contract can be upgraded by the Manager | | `caller` | `string` | Yes | Stellar address of the deployer (signs the transaction) | ### Response ```json theme={null} { "xdr": "AAAAAgAAAAB...", "simulationResponse": { ... }, "error": null } ``` Sign the returned `xdr` with the `caller`'s key and submit via `POST /send?network=testnet`. *** ## `POST /factory/create-vault-deposit` Creates a vault **and** performs the initial deposit atomically. This is the recommended approach since it handles Steps 3 and 4 in a single transaction. ```http theme={null} POST https://api.defindex.io/factory/create-vault-deposit?network=testnet Authorization: Bearer Content-Type: application/json ``` ### Request Body ```json theme={null} { "roles": { "manager": "GACKTN5D...", "emergencyManager": "GACKTN5D...", "rebalanceManager": "GACKTN5D...", "feeReceiver": "GACKTN5D..." }, "vaultFeeBps": 100, "assets": [ { "address": "CAQCFVLOBK5GIULPNZRGATJJMIZL5BSP7X5YJVMGCPTUEPFM4AVSRCJU", "strategies": [ { "address": "CALLOM5I7XLQPPOPQMYAHUWW4N7O3JKT42KQ4ASEEVBXDJQNJOALFSUY", "name": "BlendUSDC Strategy", "paused": false } ] } ], "name": "My USDC Vault", "symbol": "MUSDC", "upgradable": true, "caller": "GACKTN5D...", "depositAmounts": [10000000] } ``` ### Additional Field | Field | Type | Required | Description | | - | - | - | - | | `depositAmounts` | `number[]` | Yes | Initial deposit amounts in **stroops**, one per asset in the same order as `assets`. Must be ≥ 1001 per asset. | All other fields are identical to `create-vault` above. > **Decimal reference:** 1 USDC = `10_000_000` stroops (7 decimals). 1 XLM = `10_000_000` stroops. The minimum `1001` stroops equals **0.0001001 units**. ### Response Same shape as `create-vault`: ```json theme={null} { "xdr": "AAAAAgAAAAB...", "simulationResponse": { ... }, "error": null } ``` *** ## `POST /factory/create-vault-auto-invest` Creates a vault, makes the initial deposit, **and** immediately rebalances (invests) into strategies — all in one batched transaction. At the end it also transfers the Manager role to the final address. This is the most convenient option for fully automated deployments. ```http theme={null} POST https://api.defindex.io/factory/create-vault-auto-invest?network=testnet Authorization: Bearer Content-Type: application/json ``` ### Request Body ```json theme={null} { "caller": "GBZXUKUY...", "roles": { "manager": "GBAJGSZQ...", "emergencyManager": "GBAJGSZQ...", "rebalanceManager": "GBAJGSZQ...", "feeReceiver": "GBAJGSZQ..." }, "name": "Auto-Invest USDC Vault", "symbol": "AIUSDC", "vaultFee": 100, "upgradable": true, "assets": [ { "address": "CAQCFVLOBK5GIULPNZRGATJJMIZL5BSP7X5YJVMGCPTUEPFM4AVSRCJU", "symbol": "USDC", "amount": 10000000, "strategies": [ { "address": "CALLOM5I7XLQPPOPQMYAHUWW4N7O3JKT42KQ4ASEEVBXDJQNJOALFSUY", "name": "BlendUSDC Strategy", "amount": 10000000 } ] } ] } ``` ### Field Reference | Field | Type | Required | Description | | - | - | - | - | | `caller` | `string` | Yes | Deployer's Stellar address. Signs the transaction. The manager role is transferred from this address to `roles.manager` at the end. | | `roles.manager` | `string` | Yes | Final Manager address after deployment | | `roles.emergencyManager` | `string` | Yes | Emergency Manager address | | `roles.rebalanceManager` | `string` | Yes | Rebalance Manager address | | `roles.feeReceiver` | `string` | Yes | Fee Receiver address | | `name` | `string` | Yes | Vault display name | | `symbol` | `string` | Yes | dfToken symbol (e.g., `AIUSDC`) | | `vaultFee` | `number` | Yes | Vault fee in basis points. Note: this field is named `vaultFee` (not `vaultFeeBps`) for this endpoint. | | `upgradable` | `boolean` | Yes | Whether the vault contract can be upgraded | | `assets` | `Asset[]` | Yes | Assets to manage | | `assets[].address` | `string` | Yes | Token contract address | | `assets[].symbol` | `string` | Yes | Human-readable token symbol | | `assets[].amount` | `number` | Yes | Total deposit amount for this asset in stroops. Must be ≥ 1001 and equal to the sum of all strategy amounts. | | `assets[].strategies` | `Strategy[]` | Yes | Strategies for this asset | | `assets[].strategies[].address` | `string` | Yes | Strategy contract address | | `assets[].strategies[].name` | `string` | Yes | Strategy name | | `assets[].strategies[].amount` | `number` | Yes | Amount (in stroops) to invest into this strategy. The sum of all strategy amounts must equal `assets[].amount`. | > **Strategy amounts must sum to the asset amount.** If `assets[0].amount = 10000000`, then all `strategies[].amount` values for that asset must add up to `10000000`. ### Response ```json theme={null} { "xdr": "AAAAAgAAAAA...", "predictedVaultAddress": "CCQ2BCKKDX7HSF5TULLRFRKS4RYIC5ZZGYYTBR3XFDLZ6MMZFRJNXIEA", "warning": "The vault address is predicted from simulation. Actual address may differ if network state changes." } ``` The `predictedVaultAddress` is derived from simulation and is accurate in most cases, but treat it as advisory until the transaction confirms on-chain. *** ## Complete Testnet Example (TypeScript) This example deploys a BlendUSDC vault on testnet using the `create-vault-deposit` endpoint. > **Before running**: Make sure you have BlendUSDC in your wallet. Go to [testnet.blend.capital](https://testnet.blend.capital), connect your Freighter wallet (on Testnet), and use the faucet to receive BlendUSDC. ```typescript theme={null} const API_KEY = process.env.DEFINDEX_API_KEY!; const DEPLOYER_ADDRESS = "GACKTN5D..."; // Your Stellar testnet address const body = { roles: { manager: DEPLOYER_ADDRESS, emergencyManager: DEPLOYER_ADDRESS, rebalanceManager: DEPLOYER_ADDRESS, feeReceiver: DEPLOYER_ADDRESS, }, vaultFeeBps: 100, // 1% assets: [ { // BlendUSDC on testnet address: "CAQCFVLOBK5GIULPNZRGATJJMIZL5BSP7X5YJVMGCPTUEPFM4AVSRCJU", strategies: [ { address: "CALLOM5I7XLQPPOPQMYAHUWW4N7O3JKT42KQ4ASEEVBXDJQNJOALFSUY", name: "Blend USDC Strategy", paused: false, }, ], }, ], name: "My USDC Vault", symbol: "MUSDC", upgradable: true, caller: DEPLOYER_ADDRESS, depositAmounts: [1001], // Minimum first deposit (1001 stroops) }; // Step 1: Build the transaction const res = await fetch( "https://api.defindex.io/factory/create-vault-deposit?network=testnet", { method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${API_KEY}`, }, body: JSON.stringify(body), } ); const { xdr } = await res.json(); // Step 2: Sign with your wallet (Freighter / Privy / Crossmint) const signedXdr = await signTransaction(xdr, { network: "TESTNET" }); // Step 3: Submit const sendRes = await fetch( "https://api.defindex.io/send?network=testnet", { method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${API_KEY}`, }, body: JSON.stringify({ xdr: signedXdr }), } ); const result = await sendRes.json(); console.log("Vault deployed:", result.txHash); ``` *** ## Complete Mainnet Example (TypeScript) ```typescript theme={null} const body = { roles: { manager: "GMANAGER...", emergencyManager: "GEMERGENCY...", rebalanceManager: "GREBALANCE...", feeReceiver: "GFEERECEIVER...", }, vaultFeeBps: 50, // 0.5% assets: [ { // Real USDC on mainnet (Circle / Stellar SAC) address: "CCW67TSZV3SSS2HXMBQ5JFGCKJNXKZM7UQUWUZPUTHXSTZLEO7SJMI75", strategies: [ { address: "CDB2WMKQQNVZMEBY7Q7GZ5C7E7IAFSNMZ7GGVD6WKTCEWK7XOIAVZSAP", name: "Blend USDC Fixed Strategy", paused: false, }, ], }, ], name: "My USDC Vault", symbol: "MUSDC", upgradable: true, caller: "GDEPLOYER...", depositAmounts: [1001], // 0.0001001 USDC — the required minimum }; const res = await fetch( "https://api.defindex.io/factory/create-vault-deposit?network=mainnet", { method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${API_KEY}`, }, body: JSON.stringify(body), } ); const { xdr } = await res.json(); // ... sign and send as above ``` *** ## After Deployment: First Rebalance After the vault is deployed and the first deposit is made, call the `rebalance` function to invest funds into your chosen strategies. Without this step, all deposited funds remain **idle** (uninvested) in the vault. See the [Rebalance section in the main Create a Vault guide](/integration-guide/creating-a-defindex-vault/index#step-5-first-rebalance) for how to do this via the API or `stellar-cli`. > If you used `create-vault-auto-invest`, the initial rebalance is already done for you as part of the deployment transaction. *** ## Testnet vs Mainnet Differences at a Glance | Aspect | Testnet | Mainnet | | - | - | - | | USDC | BlendUSDC (`CAQCFV...`) — get from testnet.blend.capital | Circle USDC (`CCW67T...`) | | CETES | Testnet CETES (`CC72F5...`) — get from testnet.blend.capital | Real CETES token | | XLM | Testnet XLM — get from Friendbot | Real XLM | | Factory | `CDSCWE4...` | `CDKFHFJ...` | | API `network` param | `testnet` | `mainnet` | | Network passphrase | `Test SDF Network ; September 2015` | `Public Global Stellar Network ; September 2015` | | RPC URL | `https://soroban-testnet.stellar.org` | Provider-dependent | *** ## Troubleshooting **`StrategyDoesNotSupportAsset` (error 102)**\ The strategy address you provided does not support the asset token you specified. Double-check that the strategy address matches the asset and the strategy/asset/network relation is correct. For example, the USDC strategy cannot be used with the XLM token address or, the USDC strategy on testnet cannot be used with the USDC token address from mainnet. **Transaction fails with simulation error on testnet**\ You may not have a BlendUSDC trustline. Visit [testnet.blend.capital](https://testnet.blend.capital), connect your wallet, and add the BlendUSDC asset before trying again. **`RolesIncomplete` (error 104)**\ All four roles (0–3) must be provided. If you leave any out, the factory will reject the transaction. **`FeeTooHigh` (factory error 406)**\ The `vaultFeeBps` value exceeds the maximum allowed. Keep it at or below 9,000 (90% of yield). **`AmountNotAllowed` (error 110)**\ The initial deposit amount is zero or negative. Provide at least 1001 stroops per asset. For additional errors, see the [Troubleshooting Guide](/integration-guide/troubleshooting). # Using the Console Source: https://docs.defindex.io/integration-guide/creating-a-defindex-vault/using-the-console Create a vault by clicking, not coding. The [DeFindex Console](https://console.defindex.io) is the no-code path: it walks you through the same factory deployment the API exposes, and afterwards it is where you manage the vault day to day. > [card] [Open the Console](https://console.defindex.io) > > Create your account or log in, then pick **Create Vault**. ## Before you start 1. **Log in** at [console.defindex.io](https://console.defindex.io). The same account holds your [API keys](/integration-guide/guides-and-tutorials/getting-api-key). 2. **Pick the network** in Settings: Mainnet or Testnet. The two are completely independent, see the [requirements](/integration-guide/creating-a-defindex-vault/index#network). 3. **Connect a Stellar wallet** (Freighter, Lobstr, and others are supported). It pays the deployment fee and signs the transaction, and you need [funds on the right network](/integration-guide/creating-a-defindex-vault/index#getting-testnet-tokens). ## The Create Vault form The form mirrors the factory arguments, in four sections: 1. **Basic Info**: the vault's name and symbol, and the **vault fee** in basis points. The fee is charged on the yield, capped at 9,000 bps. See [Fees and revenue](/intro/fees). 2. **Roles**: the four addresses every vault needs: Manager, Emergency Manager, Rebalance Manager, and Fee Receiver. What each one can do is on [Vault Roles](/integration-guide/vault-roles). 3. **Options**: whether the vault is **upgradable**. This is fixed at creation, see the [trade-off](/integration-guide/creating-a-defindex-vault/index#step-1-assign-vault-roles-fees-and-upgradability). 4. **Assets**: the asset the vault accepts and the strategies backing it, with the first deposit amount. Only strategies compatible with the chosen asset are offered. A first deposit of 20 USDC helps the historical APY endpoint avoid rounding errors. Two switches decide what happens with that deposit: **Deposit on creation** makes the deposit in the same transaction, and **Auto-invest deposited funds** invests it into the strategies you chose, which is the vault's first rebalance. Keep both on. If either is off, the vault starts with no allocation and every deposit stays idle, even with `invest: true`, until you run one **Invest** from the vault's **Admin** tab. See [Deposit with `invest: true` stays idle](/integration-guide/troubleshooting#deposit-with-invest-true-stays-idle). ## Sign and confirm Review everything, then sign the transaction with your connected wallet. Once the network confirms it, the vault appears on your console dashboard, where you can deposit, rebalance, configure fees, and rotate roles from the vault's tabs. Assets and strategies cannot be added or swapped after creation by any vault function, so double-check the Assets section before signing. # Fees through the API Source: https://docs.defindex.io/integration-guide/fees The four calls that run a vault's fee. The full fee lifecycle on a deployed vault. For the model itself, read [Fees and revenue](/intro/fees). > [card] [Or do it in the Console](https://console.defindex.io) > > Your vault's Fees tab shows the current configuration and runs the same four operations with no code. ## Before you start * The **Manager** role on the vault, or the **Fee Receiver** role for the last two operations. * An [API key](/integration-guide/quickstart). * Your vault address, on mainnet or on the [Sandbox](/integration-guide/sandbox). * A way to sign transactions: Freighter, Stellar Laboratory, or your own signer. Every write below returns an unsigned XDR. You sign it and submit it with `POST /send`, the same flow as any [Vault Operation](/integration-guide/vault-operations/index). ## Basis points Fees are expressed in basis points, where `SCALAR_BPS = 10,000` is 100%. | BPS | Of the yield | | | - | - | - | | 1000 | 10% | | | 3000 | 30% | Common starting point | | 5000 | 50% | | | 9000 | 90% | The maximum the vault accepts | The vault rejects anything above 9,000. Fees apply to the **yield** a vault produces. ## Read the current configuration ```bash theme={null} curl -X GET "https://api.defindex.io/vault/YOUR_VAULT_ADDRESS?network=mainnet" \ -H "Authorization: Bearer YOUR_API_KEY" ``` ```json theme={null} { "name": "My Yield Vault", "address": "CABC...XYZ", "feesBps": { "vaultFee": 3000, "defindexFee": 5000 } } ``` * `vaultFee`: your fee on the yield. `3000` is 30%. * `defindexFee`: the DeFindex share **of that fee**, not an extra charge on your users. `5000` would be 50% of `vaultFee`. This value is stored in the vault when it is created, copied from the factory's default rate at that moment, and no vault function changes it afterwards, so it differs between vaults created at different times. Read it here rather than assuming a number. See [how DeFindex is paid](/intro/fees#how-defindex-is-paid). The fee receiver address is a separate read: ```bash theme={null} curl -X GET "https://api.defindex.io/vault/YOUR_VAULT_ADDRESS/get/fee-receiver?network=mainnet" \ -H "Authorization: Bearer YOUR_API_KEY" ``` ## Change the fee `lock-fees` does two things in one call: it locks whatever has accrued at the old rate, then sets the new one. That ordering is deliberate, so a rate change never reprices yield that was already earned. ```bash theme={null} curl -X POST "https://api.defindex.io/vault/YOUR_VAULT_ADDRESS/lock-fees?network=mainnet" \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "new_fee_bps": 3000, "caller": "GMANAGER_ADDRESS..." }' ``` | Parameter | Type | Description | | - | - | - | | `new_fee_bps` | number | New rate in BPS, 0 to 9000 | | `caller` | string | Manager address | Manager only. `new_fee_bps: 0` disables the partner fee: your users then keep all of the yield and no fee is locked for anyone. ## Change the fee receiver ```bash theme={null} curl -X POST "https://api.defindex.io/vault/YOUR_VAULT_ADDRESS/set/fee-receiver?network=mainnet" \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "new_address": "GNEW_RECEIVER_ADDRESS...", "caller": "GMANAGER_ADDRESS..." }' ``` Callable by the Manager **or** by the current Fee Receiver. Verify the address before signing: the only way back is another update from whoever holds the role afterwards. > [!WARNING] > > Give the fee receiver a trustline for every asset the vault holds before you distribute. A distribution to an address without one fails. ## Distribute ```bash theme={null} curl -X POST "https://api.defindex.io/vault/YOUR_VAULT_ADDRESS/distribute-fees?network=mainnet" \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "caller": "GMANAGER_ADDRESS..." }' ``` Callable by the Manager or the Fee Receiver. It unwinds the locked amount from the strategies and transfers it, in the same transaction, to your fee receiver and to the DeFindex protocol fee receiver, split by `defindexFee`. Fees must be locked before they can be distributed. Locking happens automatically on every deposit and withdrawal, so in practice there is usually something to distribute; `lock-fees` forces it. ## When it fails | What you see | Why | | - | - | | `Permission denied` | Only the Manager changes fees. `set/fee-receiver` and `distribute-fees` also accept the current Fee Receiver | | `Fee exceeds maximum` | Above 9,000 BPS | | `No fees to distribute` | Nothing locked since the last distribution, or the vault has not generated yield | | `401 Unauthorized` | API key missing, revoked or disabled. See [Getting an API key](/integration-guide/guides-and-tutorials/getting-api-key) | | Fails after signing | The XDR expired. Rebuild, sign and submit promptly, and check the signer holds enough XLM for network fees | ## Good practice Use a multisig for the Manager role and a dedicated wallet for the Fee Receiver. Check the BPS arithmetic before signing, since a slip of one digit is a factor of ten. Try it on the [Sandbox](/integration-guide/sandbox) before mainnet. Distribute regularly rather than letting a large balance sit locked. ## Related * [Fees and revenue](/intro/fees): the model, what your users see, how the split works. * [Stable APY](/products/stable-apy): let DeFindex move the fee for you against a target. * [Vault Roles](/integration-guide/vault-roles): who can lock, change and distribute. # Additional Resources Source: https://docs.defindex.io/integration-guide/guides-and-tutorials/additional-resources ### :globe_with_meridians: **Official Channels** * [Defindex Website](https://www.defindex.io) * [Discord ](https://discord.gg/aV5jHwmsaj) * [Defindex Documentation](https://docs.defindex.io/) * [Defindex GitHub](https://github.com/paltalabs/defindex) * [Twitter](https://x.com/paltalabs) * [LinkedIn](https://www.linkedin.com/company/paltalabs/) * [Blog Dev](https://dev.to/paltalabs) * [Medium](https://medium.com/paltalabs) # AI Tools — MCP Server & Claude Code Skill Source: https://docs.defindex.io/integration-guide/guides-and-tutorials/ai-tools DeFindex provides two complementary AI integrations that let you query documentation and build integrations using natural language. *** ## 1. DeFindex MCP Server The **Model Context Protocol (MCP)** server exposes the full DeFindex documentation to any compatible AI assistant, including Claude, so it can answer questions about vaults, strategies, API endpoints, and SDK usage without you having to paste docs manually. ### What is it? The DeFindex MCP server (`https://docs.defindex.io/mcp`) gives AI tools direct, searchable access to these docs. Ask your AI assistant about deposit flows, vault roles, APY calculations, or any other DeFindex concept and it will answer from the latest documentation. ### Add to Claude Code (CLI) Add the following to your project's `.claude/settings.json` or to your global `~/.claude/settings.json`: ```json theme={null} { "mcpServers": { "Defindex": { "type": "http", "url": "https://docs.defindex.io/mcp" } } } ``` After saving, restart Claude Code. The server will be available as `mcp__Defindex__*` tools. ### Add to Claude.ai (Web) 1. Open **Claude.ai → Settings → Integrations → Add MCP Server** 2. Enter the server URL: `https://docs.defindex.io/mcp` 3. Give it a name (e.g. `DeFindex Docs`) and save ### Add to Claude Desktop In your `claude_desktop_config.json`: ```json theme={null} { "mcpServers": { "Defindex": { "type": "http", "url": "https://docs.defindex.io/mcp" } } } ``` ### Example Queries Once configured, you can ask your AI assistant: * *"How do I deposit into a DeFindex vault?"* * *"What roles does a DeFindex vault have?"* * *"Show me the withdraw-shares endpoint"* * *"How is APY calculated in DeFindex?"* * *"What is a dfToken?"* *** ## 2. Claude Code Skill — `defindex-api` The **`defindex-api` skill** is a Claude Code playbook that gives the model a complete, structured reference for the DeFindex REST API. It covers authentication, every endpoint, request/response shapes, error handling, and code examples. ### What it does When invoked, the skill provides Claude Code with: * **Auth flow** — generate an API key in the console → send it as a Bearer token * **User operations** — deposit, withdraw, withdraw-shares, balance, APY, discover vaults * **Vault administration** — roles (get/set), rebalance, lock/release/distribute fees, rescue, pause/unpause strategies, upgrade WASM * **Factory** — create-vault, create-vault-deposit, create-vault-auto-invest * **Submit transactions** — POST `/send` for signed XDRs * **Rate limits** — tier configs and retry patterns ### Installation Clone the skill repository into your Claude Code skills directory: ```bash theme={null} git clone https://github.com/defindex-io/defindex-skill ~/.claude/skills/defindex-api ``` Or install file-by-file: ```bash theme={null} mkdir -p ~/.claude/skills/defindex-api curl -sL https://raw.githubusercontent.com/defindex-io/defindex-skill/main/SKILL.md -o ~/.claude/skills/defindex-api/SKILL.md curl -sL https://raw.githubusercontent.com/defindex-io/defindex-skill/main/auth.md -o ~/.claude/skills/defindex-api/auth.md curl -sL https://raw.githubusercontent.com/defindex-io/defindex-skill/main/endpoints.md -o ~/.claude/skills/defindex-api/endpoints.md ``` ### How to use it In Claude Code, type: ``` /defindex-api ``` Or reference it in your prompt: ``` Use the defindex-api skill to help me deposit 100 USDC into the mainnet vault ``` Argument hints: | Argument | What you get | | - | - | | `auth` | Registration, login, API key generation | | `vault` | Vault info, balance, APY | | `deposit` | Deposit flow with code example | | `withdraw` | Withdraw and withdraw-shares | | `admin` | Roles, rebalance, fees, rescue, pause, upgrade | | `factory` | Create vault, create-vault-deposit, auto-invest | | `send` | Submit signed XDR | | `rate-limits` | Tier configs, 429 handling | ### Related Skills * **`stellar-dev`** — general Stellar and Soroban development playbook. *** ## Getting Your API Key Before you can call protected endpoints, you need an API key: 1. Open the [**DeFindex Console**](https://console.defindex.io/) and create your account, or log in. A new account verifies its email with a 6-digit code first. 2. Go to **API Keys**, name the key and click **Create API Key**. See the full walkthrough: [Getting Your API Key](/integration-guide/guides-and-tutorials/getting-api-key) *** ## Additional Resources * [DeFindex API Claude Code Skill](https://github.com/defindex-io/defindex-skill) * [Full API Reference](/api-reference) * [Discord — developer channel](https://discord.gg/aV5jHwmsaj) # Beginner Guide Source: https://docs.defindex.io/integration-guide/guides-and-tutorials/beginner-guide ## 📖 What You'll Learn This guide teaches you how to integrate DeFindex API into your application using: * **Freighter Wallet** for secure wallet connection and transaction signing * **DeFindex API** for creating yield-generating vault deposits and withdrawals * **Vault concepts** like dfTokens (vault shares) and investment strategies ## 🎯 Prerequisites Before starting, make sure you have: * Basic knowledge of **HTML, CSS, and JavaScript** * **Freighter Wallet** extension installed * An **API key** from DeFindex — follow the [Getting Your API Key guide](/integration-guide/guides-and-tutorials/getting-api-key) to register and create one * A **web browser** with developer tools * **5-10 minutes** of focused time ## 🏗️ Project Structure Overview Our vault deposit application consists of **6 main parts**: ``` 1. HTML Structure → User interface elements with professional styling 2. External Libraries → Freighter API for wallet integration 3. Configuration → Centralized CONFIG object with vault and API settings 4. Application State → Tracks wallet connection and vault transaction status 5. Utility Functions → Helper functions for UI updates and API calls 6. Core Functions → Connect, Deposit, Sign, and Send (4 separate steps) ``` Since this guide is to use the DeFindex API, we'll focus on the **core functions** that make vault deposits happen. ## 🔧 Core Functions Explained ### Function 1: Connect to Wallet 🔗 ```javascript theme={null} async function connectStellarWallet() { // Step 1: Check if Freighter wallet is installed const hasFreighter = await freighter.isConnected(); console.log('Freighter connected:', hasFreighter); // Step 2: If not installed, show error message if (!hasFreighter.isConnected) { alert('Please install the Freighter wallet extension first.'); return; // Stop function execution } // Step 3: Request permission to connect console.log('Connecting to Freighter...'); account = await freighter.requestAccess(); account = account.address; // Extract just the address // Step 4: Update the user interface connectButton.disabled = true; // Disable connect button document.getElementById('account').innerText = `Connected account: ${account}`; } ``` **🔍 What this function does:** 1. **Checks** if Freighter wallet is available 2. **Requests** permission to access the wallet 3. **Stores** the wallet address for later use 4. **Updates** the UI to show connection status **🚨 Common issues:** * User doesn't have Freighter installed → Show installation instructions * User denies permission → Ask them to try again ### Function 2: Get Vault Info and Build Deposit Transaction 💰 ```javascript theme={null} async function getVaultInfoAndDeposit() { try { // Make sure wallet is connected if (!appState.connected) { updateStatus('❌ Please connect your wallet first!', 'error'); return; } // PHASE 1: Get Vault Information updateStatus('🔄 Getting vault information...', 'info'); appState.vaultInfo = await makeAPIRequest(`/vault/${CONFIG.VAULT_ADDRESS}`, null, 'GET'); updateStatus(`✅ Vault loaded: ${appState.vaultInfo.name}
🔄 Building deposit transaction...`, 'info'); // PHASE 2: Build Deposit Transaction const depositRequest = { amounts: [CONFIG.DEPOSIT.AMOUNT], // Amount to deposit (1 XLM) caller: appState.walletAddress, // Who's depositing invest: CONFIG.DEPOSIT.INVEST, // Auto-invest into strategies slippageBps: CONFIG.DEPOSIT.SLIPPAGE // Slippage tolerance }; const buildResult = await makeAPIRequest(`/vault/${CONFIG.VAULT_ADDRESS}/deposit`, depositRequest); appState.unsignedXdr = buildResult.xdr; // Show the unsigned transaction for educational purposes ELEMENTS.unsignedXdr.value = buildResult.xdr; ELEMENTS.technicalDetails.classList.remove('hidden'); updateStatus(`✅ Deposit transaction built!
⏳ Ready for signing...`, 'info'); updateButtonStates(); } catch (error) { console.error('Vault deposit process failed:', error); updateStatus(`❌ Process failed: ${error.message}`, 'error'); } } ``` **🔍 What this function does:** 1. **Validates** wallet connection first 2. **Fetches** vault information (name, assets, strategies) 3. **Builds** a deposit transaction for the specified amount 4. **Prepares** the transaction for signing (stores in app state) 5. **Updates** the UI to enable the next step **🚨 Common issues:** * Wallet not connected → Connect wallet first * API key rejected → The key was revoked or disabled. Check its status in the [console](https://console.defindex.io/), or create a new one (see [Getting Your API Key](/integration-guide/guides-and-tutorials/getting-api-key)) * Insufficient balance → Make sure wallet has enough XLM * Vault not found → Check vault address and network ### Function 3: Sign the Transaction ✍️ ```javascript theme={null} async function signTransaction() { try { // Make sure wallet is connected and we have a transaction to sign if (!appState.connected) { updateStatus('❌ Please connect your wallet first!', 'error'); return; } if (!appState.unsignedXdr) { updateStatus('❌ No transaction to sign. Please get a quote first!', 'error'); return; } updateStatus('📝 Please approve the transaction in Freighter...', 'info'); // Sign the transaction using Freighter const signResult = await freighterAPI.signTransaction(appState.unsignedXdr, { network: CONFIG.NETWORK, networkPassphrase: 'Test SDF Network ; September 2015', address: appState.walletAddress }); appState.signedTransaction = signResult.signedTxXdr; // Show the signed transaction for educational purposes ELEMENTS.signedXdr.value = appState.signedTransaction; const depositAmount = formatAmount(CONFIG.DEPOSIT.AMOUNT, 7); updateStatus(`✅ Transaction signed successfully!
📋 Ready to deposit ${depositAmount} XLM into vault`, 'success'); updateButtonStates(); } catch (error) { console.error('Transaction signing failed:', error); updateStatus(`❌ Transaction signing failed: ${error.message}`, 'error'); } } ``` **🔍 What this function does:** 1. **Validates** wallet connection and transaction availability 2. **Calls** Freighter to sign the transaction 3. **Stores** the signed transaction in app state 4. **Updates** UI to enable final step **🚨 Common issues:** * User rejects signing → Ask them to try again * Freighter not connected → Check wallet connection * Wrong network → Ensure Freighter is on testnet ### Function 4: Send Transaction to Network 🚀 ```javascript theme={null} async function sendTransaction() { try { // Make sure we have a signed transaction if (!appState.signedTransaction) { updateStatus('❌ No signed transaction available. Please get a quote and sign it first.', 'error'); return; } updateStatus('🚀 Broadcasting transaction to Stellar network...', 'info'); // Send the signed transaction const sendRequest = { xdr: appState.signedTransaction // The signed transaction }; const sendResult = await makeAPIRequest('/send', sendRequest); // Create link to view transaction on Stellar Expert const explorerUrl = `https://stellar.expert/explorer/${CONFIG.NETWORK}/tx/${sendResult.txHash}`; // Show success message ELEMENTS.transactionLink.innerHTML = ` Transaction Hash: ${sendResult.txHash}
🔗 View on Stellar Expert `; ELEMENTS.finalResults.classList.remove('hidden'); updateStatus('🎉 Vault deposit completed successfully! You now own vault shares (dfTokens). Check the transaction link above.', 'success'); // Reset state for potential next transaction appState.unsignedXdr = null; appState.signedTransaction = null; appState.currentQuote = null; updateButtonStates(); } catch (error) { console.error('Transaction send failed:', error); updateStatus(`❌ Transaction failed: ${error.message}`, 'error'); } } ``` **🔍 What this function does:** 1. **Validates** we have a signed transaction ready 2. **Submits** the transaction to the Stellar network through the DeFindex API 3. **Shows** success message with transaction hash and explorer link 4. **Resets** state for potential next transaction ## 🔄 Complete Workflow Summary **4-Step Process:** ``` 🔗 STEP 1: Connect Wallet User clicks "Connect Freighter Wallet" ↓ connectWallet() function App connects to Freighter wallet ✅ ↓ 💰 STEP 2: Get Vault Info & Build Deposit User clicks "Deposit into Vault (1 XLM)" ↓ getVaultInfoAndDeposit() function App gets vault info + builds unsigned deposit transaction ✅ ↓ ✍️ STEP 3: Sign Transaction User clicks "Sign Transaction" ↓ signTransaction() function User approves transaction in Freighter wallet ✅ ↓ 🚀 STEP 4: Send to Network User clicks "Send Transaction" ↓ sendTransaction() function App broadcasts to Stellar network ✅ ↓ 🎉 VAULT DEPOSIT COMPLETE! ``` ## 🛠️ Key Concepts for Beginners ### What is XDR? **XDR** (External Data Representation) is how Stellar transactions are encoded: * **Unsigned XDR**: Transaction ready to be signed * **Signed XDR**: Transaction with digital signature, ready to submit ### What is a Vault? A **vault** is a smart contract that: * Holds multiple users' assets * Automatically invests them in yield-generating strategies * Issues **dfTokens** (vault shares) representing ownership ### What are dfTokens? **dfTokens** are like receipts for your vault deposit: * Represent your proportional share of the vault * Increase in value as the vault earns yield * Can be redeemed for underlying assets + profits ### What are Strategies? **Strategies** are investment protocols that: * Generate yield on deposited assets * Examples: Blend Capital lending, liquidity providing * Vaults can use multiple strategies to maximize returns ### What is Signing? **Signing** a transaction means: * Proving you own the wallet * Authorizing the vault deposit * Making it ready for the network ## 🚨 Security Best Practices ### ✅ DO: * Use testnet for learning and testing * Keep your API keys secure * Verify transaction details before signing * Start with small amounts ### ❌ DON'T: * Put API keys in public code repositories * Sign transactions you don't understand * Use mainnet while learning * Hardcode private keys (never!) ## 🔧 Common Troubleshooting ### Problem: "Freighter not found" **Solution**: Install Freighter wallet extension ### Problem: "401 Unauthorized" error **Solution**: Check you send your API key as `Authorization: Bearer `, and that the key is active in the console ### Problem: "Insufficient balance" **Solution**: Make sure you have enough XLM in your wallet for the deposit ### Problem: Transaction fails **Solution**: Check you have enough XLM for fees and minimum deposit requirements ## 🎓 Next Steps Once you understand this basic example: 1. **Customize the UI** with better styling 2. **Add error handling** for better user experience 3. **Support multiple vaults** with different asset combinations 4. **Add APY tracking** to show vault performance 5. **Try withdrawal functionality** to redeem your dfTokens 6. **Learn about strategies** and how they generate yield ## 📚 Additional Resources * **DeFindex API reference**: [docs.defindex.io/api-reference](/api-reference) * **DeFindex Discord**: [https://discord.gg/aV5jHwmsaj](https://discord.gg/aV5jHwmsaj) * **Freighter Docs**: [https://freighter.app/docs](https://freighter.app/docs) * **Stellar Docs**: [https://developers.stellar.org](https://developers.stellar.org) * **Stellar Expert**: [https://stellar.expert](https://stellar.expert) (blockchain explorer) * **DeFindex**: [https://defindex.io](https://defindex.io) ## 💡 Pro Tips 1. **Use browser dev tools** to debug API calls 2. **Check the console** for error messages 3. **Read API responses** to understand what's happening # Crossmint Smart Wallets Integration Source: https://docs.defindex.io/integration-guide/guides-and-tutorials/crossmint-smart-wallets > [!NOTE] > > To move native USDC from Base or another EVM chain with Circle CCTP instead of Sodax, see [USDC from Base with CCTP and Crossmint](/advanced-documentation/crossmint-cctp). This guide and its repository predate CCTP on Stellar. ## Overview This guide points to a reference repository that shows you how to integrate DeFindex vaults using **Crossmint smart wallets** — enabling fully automated, server-side deposits, withdrawals, and cross-chain bridging with **zero user interaction**. The pattern uses an **EVM private key registered as `adminSigner`** to control both an ERC-4337 smart wallet on Base and a Stellar smart wallet. All Defindex vault interactions go through Crossmint's REST API as Soroban `contract-call` transactions — no manual XDR construction required. ## Repository [**defindex-io/crossmint-defindex-guide**](https://github.com/defindex-io/crossmint-defindex-guide) ## What the Repository Covers | Topic | Description | | - | - | | Crossmint setup | Server API key (`sk_`), wallet email, staging vs production | | EVM wallet | ERC-4337 smart wallet on Base with `external-wallet` adminSigner | | Stellar wallet | Stellar smart wallet with auto-XLM funding, Soroban contract-call signing | | Deposit | `contract-call` via Crossmint REST → base64 XDR approval → poll | | Withdraw | Withdraw by amount or by shares (% redemption) | | Bridge | Base USDC → Stellar → Defindex vault via Sodax | | Gotchas | 9 documented edge cases with root causes and fixes | ## Architecture at a Glance ``` Your Server (EVM Private Key as adminSigner) │ ▼ Crossmint REST API (api/2025-06-09) ├── EVM Smart Wallet (ERC-4337, Base) │ POST /transactions → sign hex bytes → POST /approvals → onChain.txId └── Stellar Smart Wallet POST /transactions (contract-call) → sign base64 XDR → POST /approvals → onChain.txId Sodax Bridge └── Base USDC → Stellar USDC (via Sonic hub, no Horizon polling needed) Defindex Vault (Soroban) ├── method: deposit → amounts_desired, amounts_min, from, invest ├── method: withdraw → amounts_to_withdraw, from └── method: withdraw_shares → shares_amount, from ``` All vault operations follow the same pattern: 1. `POST` to Crossmint REST → create `contract-call` transaction 2. Response is `awaiting-approval` with a base64-encoded XDR message 3. Sign with `keypair.sign(Buffer.from(message, "base64"))` using `STELLAR_SERVER_KEY` 4. `POST` signature to `/approvals` 5. Poll until `onChain.txId` is returned ## Quick Start ```bash theme={null} git clone https://github.com/defindex-io/crossmint-defindex-guide cd crossmint-defindex-guide pnpm install cp .env.example .env # Fill in: CROSSMINT_SERVER_API_KEY (sk_...), CROSSMINT_WALLET_EMAIL, # EVM_PRIVATE_KEY, STELLAR_SERVER_KEY ``` ```bash theme={null} CROSSMINT_ENV=staging pnpm example:deposit # Deposit into testnet vault CROSSMINT_ENV=staging pnpm example:withdraw # Withdraw by amount (testnet) CROSSMINT_ENV=staging pnpm example:withdraw-shares # Withdraw by shares (testnet) CROSSMINT_ENV=production pnpm example:bridge # Base USDC → Stellar → Defindex vault (mainnet) ``` ## Prerequisites * [Crossmint](https://crossmint.com) account with a **server API key** (must start with `sk_`, not `ck_`) * `EVM_PRIVATE_KEY` — becomes the `adminSigner` of the EVM smart wallet on Base * `STELLAR_SERVER_KEY` — Stellar ed25519 secret key, becomes the `adminSigner` of the Stellar wallet * Defindex API key — generate one at [console.defindex.io](https://console.defindex.io/) under **API Keys** ## Additional Resources * [Crossmint Documentation](https://docs.crossmint.com) * [Defindex API Reference](/api-reference) * [Sodax Bridge Documentation](https://docs.sodax.io) # Deposit & Transfer dfTokens Source: https://docs.defindex.io/integration-guide/guides-and-tutorials/deposit-and-transfer-dftokens ## 📖 What You'll Learn In this tutorial you'll build a TypeScript script that: * **Deposits** assets into a DeFindex vault and receives dfTokens in return * **Transfers** those dfTokens to another Stellar wallet By the end, you'll have a working script that automates this entire flow — useful for vault managers who want to run **raffles**, **airdrops**, or distribute **incentives** to their users. ## 💡 Why Would I Want to Transfer dfTokens? When you deposit into a DeFindex vault, the vault mints **dfTokens** — tokens that represent your proportional share of the vault's assets. These tokens: * Increase in value as the vault earns yield * Can be redeemed later for the underlying assets + profits * **Are transferable**, just like any other Stellar token This means a vault manager can deposit funds, receive dfTokens, and then **distribute them to other wallets**. The recipients now hold vault shares without needing to deposit themselves. Some practical use cases: | Use Case | Description | | - | - | | 🎁 Raffles & Giveaways | Deposit and distribute dfTokens as prizes | | 🏆 User Incentives | Reward active users with yield-bearing tokens | | 💼 Team Distribution | Split vault ownership across team members | | 🔄 OTC Transfers | Move vault positions between wallets | ## 🎯 Prerequisites Before starting, make sure you have: * **Node.js** (v18+) and a package manager (`npm`, `yarn`, or similar) * A **Stellar wallet** with enough balance for the deposit + transaction fees * A **DeFindex API key** — generate one at [console.defindex.io](https://console.defindex.io/) under **API Keys** * Basic knowledge of **TypeScript** and the **Stellar network** ## 🧠 Key Concepts Before diving into code, let's understand the two core operations we'll perform. ### Deposit → Mint dfTokens When you call `deposit` on a DeFindex vault, the contract: 1. Transfers your assets (e.g., XLM) from your wallet into the vault 2. Calculates how many shares you should receive, proportional to your contribution 3. **Mints dfTokens** to your wallet representing those shares 4. Optionally invests the deposited funds into the vault's strategies The vault contract's deposit function signature looks like this: ```rust theme={null} fn deposit( e: Env, amounts_desired: Vec, amounts_min: Vec, from: Address, invest: bool, ) -> Result<(Vec, i128, Option>>), ContractError> ``` It returns a tuple with: the actual deposited amounts, the **number of dfTokens minted**, and the investment allocations. ### Transfer dfTokens Here's something important: **the vault contract itself is the dfToken contract**. The vault implements the standard Stellar token interface, which means you can call `transfer` directly on the vault contract to move dfTokens between wallets: ```rust theme={null} fn transfer(e: Env, from: Address, to: Address, amount: i128) ``` No separate token contract needed — just call `transfer` on the vault address with the sender, receiver, and amount. ## 🏗️ Step-by-Step Implementation ### Step 1: Project Setup Create a new project and install the required dependencies: ```bash theme={null} mkdir defindex-deposit-transfer cd defindex-deposit-transfer npm init -y npm install @defindex/sdk @stellar/stellar-sdk npm install -D typescript tsx @types/node dotenv ``` Add a run script to your `package.json`: ```json theme={null} { "scripts": { "start": "tsx src/index.ts" } } ``` Create a `tsconfig.json`: ```json theme={null} { "compilerOptions": { "target": "ES2020", "module": "CommonJS", "rootDir": "src", "outDir": "dist", "strict": true, "esModuleInterop": true, "moduleResolution": "node", "resolveJsonModule": true, "skipLibCheck": true }, "include": ["src/**/*.ts"], "exclude": ["node_modules"] } ``` Create a `.env` file with your configuration: ```bash theme={null} DEFINDEX_API_KEY=sk_your_api_key_here STELLAR_SECRET_KEY=S_your_wallet_secret_key RECEIVER_ADDRESS=G_receiver_wallet_public_key SOROBAN_RPC=your testnet soroban rpc url (e.g., https://soroban-testnet.stellar.org) ``` > ⚠️ **Never commit your `.env` file to version control.** Add it to your `.gitignore`. > > **Note:** This tutorial uses **testnet** for learning purposes. For production, change `SOROBAN_RPC` to a mainnet endpoint (e.g., `https://soroban-rpc.mainnet.stellar.gateway.fm`) and update the network references in the code to `Networks.PUBLIC` / `SupportedNetworks.MAINNET`. ### Step 2: Load Configuration Create `src/index.ts` and start by importing dependencies and loading environment variables: ```typescript theme={null} import { DefindexSDK, SupportedNetworks } from '@defindex/sdk'; import { rpc, Keypair, Networks, TransactionBuilder, Transaction, Contract, Address, BASE_FEE, xdr, scValToNative, nativeToScVal, } from '@stellar/stellar-sdk'; import { config } from 'dotenv'; config(); ``` Define your constants. You'll need to update `VAULT_ADDRESS` to match the vault you want to deposit into: ```typescript theme={null} // ─── Constants ─────────────────────────────────────────────── const VAULT_ADDRESS = 'YOUR_VAULT_ADDRESS_HERE'; // ← Replace with your vault const DECIMALS = 7; const DEPOSIT_AMOUNT = 10; // Human-readable amount const DEPOSIT_AMOUNT_RAW = BigInt(Math.round(DEPOSIT_AMOUNT * 10 ** DECIMALS)); ``` > **About decimals:** Stellar uses 7 decimal places for most assets. So `10 XLM` = `100,000,000` stroops (base units). Always convert to raw amounts before calling contract functions. We use `BigInt(Math.round(...))` to avoid floating-point precision issues with non-integer amounts like `0.5`. Now load and validate the environment variables: ```typescript theme={null} // ─── Environment ───────────────────────────────────────────── interface EnvConfig { apiKey: string; secretKey: string; receiverAddress: string; sorobanRpc: string; } function loadEnv(): EnvConfig { const apiKey = process.env.DEFINDEX_API_KEY; const secretKey = process.env.STELLAR_SECRET_KEY; const receiverAddress = process.env.RECEIVER_ADDRESS; const sorobanRpc = process.env.SOROBAN_RPC; const missing: string[] = []; if (!apiKey) missing.push('DEFINDEX_API_KEY'); if (!secretKey) missing.push('STELLAR_SECRET_KEY'); if (!receiverAddress) missing.push('RECEIVER_ADDRESS'); if (!sorobanRpc) missing.push('SOROBAN_RPC'); if (missing.length > 0) { console.error(`Missing environment variables: ${missing.join(', ')}`); process.exit(1); } return { apiKey: apiKey!, secretKey: secretKey!, receiverAddress: receiverAddress!, sorobanRpc: sorobanRpc!, }; } ``` ### Step 3: Transaction Helper Both deposit and transfer need to submit a transaction and wait for on-chain confirmation. Let's create a reusable helper: ```typescript theme={null} // ─── Transaction Helpers ───────────────────────────────────── interface TxResult { txHash: string; returnValue?: xdr.ScVal; } const MAX_POLLS = 30; // 30 polls × 2s = 60s max wait async function sendAndConfirm( rpcServer: rpc.Server, transaction: Transaction ): Promise { const response = await rpcServer.sendTransaction(transaction); if (response.status !== 'PENDING') { const errorXdr = response.errorResult?.toXDR('base64'); if (errorXdr) { const errorName = xdr.TransactionResult.fromXDR(errorXdr, 'base64') .result() .switch().name; throw new Error(`Transaction rejected: ${errorName}`); } throw new Error(`Transaction rejected with status: ${response.status}`); } const txHash = response.hash; console.log(` Submitted: ${txHash}`); console.log(' Waiting for confirmation...'); // Poll until confirmed, failed, or timeout for (let i = 0; i < MAX_POLLS; i++) { await new Promise((resolve) => setTimeout(resolve, 2000)); const txResponse = await rpcServer.getTransaction(txHash); if (txResponse.status === 'SUCCESS') { const successResponse = txResponse as rpc.Api.GetSuccessfulTransactionResponse; return { txHash, returnValue: successResponse.returnValue }; } if (txResponse.status === 'FAILED') { throw new Error(`Transaction failed on-chain: ${txHash}`); } } throw new Error( `Transaction not confirmed after ${MAX_POLLS * 2}s: ${txHash}` ); } ``` **🔍 What this function does:** 1. **Submits** the signed transaction to the Soroban RPC 2. **Validates** the transaction was accepted (status `PENDING`) 3. **Polls** every 2 seconds (up to 60s) until the transaction is confirmed or fails 4. **Returns** the transaction hash and the on-chain return value ### Step 4: The Deposit Function 💰 This function uses the DeFindex SDK to build a deposit transaction, signs it locally, and submits it. The key part is **extracting the minted dfTokens** from the return value: ```typescript theme={null} // ─── Deposit ───────────────────────────────────────────────── async function deposit( sdk: DefindexSDK, rpcServer: rpc.Server, keypair: Keypair ): Promise<{ txHash: string; dfTokensMinted: bigint }> { const caller = keypair.publicKey(); console.log(' Building deposit via SDK...'); const depositResponse = await sdk.depositToVault( VAULT_ADDRESS, { amounts: [DEPOSIT_AMOUNT_RAW], caller, invest: true }, SupportedNetworks.TESTNET ); console.log(' Signing...'); const tx = TransactionBuilder.fromXDR( depositResponse.xdr, Networks.TESTNET ) as Transaction; tx.sign(keypair); console.log(' Sending deposit...'); const { txHash, returnValue } = await sendAndConfirm(rpcServer, tx); if (!returnValue) { throw new Error('Deposit transaction returned no value'); } // The deposit function returns a tuple: // Index 0: Vec → actual amounts deposited // Index 1: i128 → dfTokens minted ← this is what we need // Index 2: Option → investment allocations const nativeResult = scValToNative(returnValue); if (!Array.isArray(nativeResult) || nativeResult[1] == null) { throw new Error('Unexpected deposit return shape'); } const dfTokensMinted = BigInt(nativeResult[1] as string | number | bigint); return { txHash, dfTokensMinted }; } ``` **🔍 What this function does:** 1. **Builds** an unsigned deposit transaction using the DeFindex SDK (`depositToVault`) 2. **Signs** the transaction with your keypair 3. **Submits** it to the network and waits for confirmation 4. **Parses** the return value to extract how many dfTokens were minted > **Why `invest: true`?** When set to `true`, the vault automatically allocates your deposited funds into its yield-generating strategies. Set to `false` if you want the funds to remain idle in the vault. > > **Tip:** You can also pass `slippageBps` in the deposit params (e.g., `slippageBps: 100` for 1% tolerance) to control slippage during deposit. > > **Note:** The number of dfTokens minted is **not** 1:1 with the deposited amount. dfTokens represent your proportional share of the vault — their quantity depends on the vault's current share price, which changes as the vault earns yield. ### Step 5: The Transfer Function 🔄 Now the interesting part — transferring dfTokens to another wallet. Since the vault contract implements the token interface, we call `transfer` directly on the vault contract address: ```typescript theme={null} // ─── Transfer dfTokens ────────────────────────────────────── async function transferDfTokens( rpcServer: rpc.Server, keypair: Keypair, toAddress: string, amount: bigint ): Promise { const from = keypair.publicKey(); const contract = new Contract(VAULT_ADDRESS); // Build the transfer operation on the vault contract const operation = contract.call( 'transfer', new Address(from).toScVal(), new Address(toAddress).toScVal(), nativeToScVal(amount, { type: 'i128' }) ); // Create the transaction const account = await rpcServer.getAccount(from); const tx = new TransactionBuilder(account, { fee: BASE_FEE, networkPassphrase: Networks.TESTNET, }) .addOperation(operation) .setTimeout(30) .build(); // Simulate to estimate resources console.log(' Simulating transfer...'); const simulation = await rpcServer.simulateTransaction(tx); if (rpc.Api.isSimulationError(simulation)) { throw new Error(`Transfer simulation failed: ${simulation.error}`); } // Assemble with simulation results, sign, and send const preparedTx = rpc.assembleTransaction(tx, simulation).build(); preparedTx.sign(keypair); console.log(' Sending transfer...'); const { txHash } = await sendAndConfirm(rpcServer, preparedTx); return txHash; } ``` **🔍 What this function does:** 1. **Creates** a `Contract` instance pointing to the vault address 2. **Builds** a `transfer(from, to, amount)` call — this is the standard Soroban token transfer 3. **Simulates** the transaction to estimate the required resources (CPU, memory, ledger I/O) 4. **Assembles** the final transaction with the simulation results 5. **Signs** and **submits** it to the network > **Why simulate first?** Soroban smart contract calls require accurate resource estimation. The simulation step calculates CPU instructions, memory bytes, and ledger operations needed, so the transaction has the right resource limits to succeed on-chain. > > **About fees:** `BASE_FEE` is the minimum fee (100 stroops). On a congested network, transactions with the minimum fee may be dropped. For production, consider using a higher fee (e.g., `String(100 * 10)`) or implementing a fee-bumping strategy. ### Step 6: Put It All Together 🚀 Finally, wire everything up in a `main` function: ```typescript theme={null} // ─── Main ──────────────────────────────────────────────────── async function main(): Promise { const { apiKey, secretKey, receiverAddress, sorobanRpc } = loadEnv(); const keypair = Keypair.fromSecret(secretKey); const walletA = keypair.publicKey(); const walletB = receiverAddress; const rpcServer = new rpc.Server(sorobanRpc); const sdk = new DefindexSDK({ apiKey }); console.log('='.repeat(60)); console.log('DeFindex: Deposit & Transfer dfTokens'); console.log('='.repeat(60)); console.log(` Wallet A (depositor): ${walletA}`); console.log(` Wallet B (receiver): ${walletB}`); console.log(` Vault: ${VAULT_ADDRESS}`); console.log(` Deposit: ${DEPOSIT_AMOUNT} XLM`); console.log('='.repeat(60)); console.log(''); // Step 1: Deposit into vault → receive dfTokens console.log('[Step 1] Depositing into vault...'); const { txHash: depositTxHash, dfTokensMinted } = await deposit( sdk, rpcServer, keypair ); console.log(` ✅ Deposit confirmed: ${depositTxHash}`); console.log(` dfTokens minted: ${dfTokensMinted}`); console.log(''); // Step 2: Transfer dfTokens to Wallet B console.log(`[Step 2] Transferring ${dfTokensMinted} dfTokens to Wallet B...`); const transferTxHash = await transferDfTokens( rpcServer, keypair, walletB, dfTokensMinted ); console.log(` ✅ Transfer confirmed: ${transferTxHash}`); console.log(''); // Summary console.log('='.repeat(60)); console.log('DONE'); console.log('='.repeat(60)); console.log(` Deposited: ${DEPOSIT_AMOUNT} XLM`); console.log(` dfTokens: ${dfTokensMinted}`); console.log(` Transferred to: ${walletB}`); console.log(` Deposit TX: ${depositTxHash}`); console.log(` Transfer TX: ${transferTxHash}`); console.log('='.repeat(60)); } main().catch((error: unknown) => { console.error('Fatal error:', error); process.exit(1); }); ``` ### Run It ```bash theme={null} npm start ``` You should see output similar to: ```text theme={null} ============================================================ DeFindex: Deposit & Transfer dfTokens ============================================================ Wallet A (depositor): GABC... Wallet B (receiver): GXYZ... Vault: CVAULT... Deposit: 10 XLM ============================================================ [Step 1] Depositing into vault... Building deposit via SDK... Signing... Sending deposit... Submitted: abc123... Waiting for confirmation... ✅ Deposit confirmed: abc123... dfTokens minted: 19850000 [Step 2] Transferring 19850000 dfTokens to Wallet B... Simulating transfer... Sending transfer... Submitted: def456... ✅ Transfer confirmed: def456... ============================================================ DONE ============================================================ ``` ## 🚨 Troubleshooting | Problem | Solution | | - | - | | `Missing environment variables` | Check that your `.env` file has all four variables filled in | | `Transaction rejected` | Verify Wallet A has enough asset balance and XLM for fees | | `Transfer simulation failed` | Confirm the vault address is correct and Wallet A holds dfTokens | | `Deposit returned no value` | May be a network issue — check your Soroban RPC endpoint | | `Transaction failed on-chain` | Check the transaction on [Stellar Expert](https://stellar.expert) for details | | `Transaction not confirmed after 60s` | The RPC node may have dropped the tx — check your Soroban RPC endpoint or retry with a higher fee | ## 🎓 Next Steps * **Withdraw** — Redeem dfTokens back for the underlying assets: [Withdraw Guide](/integration-guide/vault-operations/withdraw) * **Check Balances** — Query dfToken holdings: [Get Balance](/integration-guide/vault-operations/get-balance) * **Monitor APY** — Track vault performance: [Get APY](/integration-guide/vault-operations/get-apy) *** ## 🤖 Build It with AI Want to build this script quickly? Copy the prompt below and paste it into a new Claude Code session. It contains all the technical details needed to generate the complete implementation: ````text theme={null} Build a TypeScript script that deposits assets into a DeFindex vault and transfers the minted dfTokens to another wallet on the Stellar testnet. ## Technical Context - DeFindex vaults are Soroban smart contracts on Stellar that accept asset deposits and mint dfTokens (vault share tokens) in return - The vault contract itself implements the Soroban token interface, so dfTokens can be transferred by calling `transfer` directly on the vault contract address - The deposit function returns a tuple where index [1] is the number of dfTokens minted (i128) ## Required Dependencies ```bash npm install @defindex/sdk @stellar/stellar-sdk npm install -D typescript tsx @types/node dotenv ``` Use your preferred package manager (`npm`, `yarn`, etc.). Install the latest versions. ## Environment Variables (.env) ``` DEFINDEX_API_KEY= # DeFindex API key (sk_...) STELLAR_SECRET_KEY= # Wallet A secret key (depositor/signer) RECEIVER_ADDRESS= # Wallet B public key (receives dfTokens) SOROBAN_RPC=your testnet soroban rpc url ``` ## Implementation Requirements Create `src/index.ts` with the following structure: ### 1. Constants - `VAULT_ADDRESS`: The target vault contract address (user must configure) - `DECIMALS = 7` (Stellar standard) - `DEPOSIT_AMOUNT`: Human-readable amount, converted to raw (amount * 10^7) ### 2. `loadEnv()` function - Load and validate all four environment variables - Exit with error if any are missing - Return typed config object ### 3. `sendAndConfirm(rpcServer, transaction)` helper - Send transaction to Soroban RPC via `rpcServer.sendTransaction()` - Check status is 'PENDING', otherwise parse error from `response.errorResult` - Poll `rpcServer.getTransaction(hash)` every 2 seconds until SUCCESS or FAILED (max 30 polls / 60s timeout) - On SUCCESS, return `{ txHash, returnValue }` from `GetSuccessfulTransactionResponse` ### 4. `deposit(sdk, rpcServer, keypair)` function - Use `sdk.depositToVault(VAULT_ADDRESS, { amounts: [RAW_AMOUNT], caller, invest: true }, SupportedNetworks.TESTNET)` to build unsigned XDR - Parse XDR with `TransactionBuilder.fromXDR(xdr, Networks.TESTNET)` - Sign with keypair, send via `sendAndConfirm()` - Parse return value: `StellarSdk.scValToNative(returnValue)` returns an array, index [1] is dfTokens minted as bigint - Return `{ txHash, dfTokensMinted }` ### 5. `transferDfTokens(rpcServer, keypair, toAddress, amount)` function - Create `new Contract(VAULT_ADDRESS)` instance - Build operation: `contract.call('transfer', Address(from).toScVal(), Address(to).toScVal(), nativeToScVal(amount, { type: 'i128' }))` - Get account via `rpcServer.getAccount(from)` - Build transaction with `TransactionBuilder`, fee `BASE_FEE`, network `Networks.TESTNET`, timeout 30s - Simulate with `rpcServer.simulateTransaction(tx)`, check for errors with `rpc.Api.isSimulationError()` - Assemble with `rpc.assembleTransaction(tx, simulation).build()` - Sign and send via `sendAndConfirm()` ### 6. `main()` function - Load env, create Keypair, rpc.Server, and DefindexSDK instances - Step 1: Call deposit, log the deposit tx hash and dfTokens minted - Step 2: Call transferDfTokens with the minted amount, log the transfer tx hash - Print summary with all transaction details ## Run Script Add `"start": "tsx src/index.ts"` to package.json scripts. ## Important Notes - Use `Networks.TESTNET` and `SupportedNetworks.TESTNET` for testnet - For production, switch to `Networks.PUBLIC` / `SupportedNetworks.MAINNET` and a mainnet RPC endpoint - All amounts use 7 decimals (stroops) - The vault contract address is used both for deposit (via SDK) and for the transfer call (as a Contract instance) - Handle errors with try/catch — re-throw or call `process.exit(1)` on fatal errors - Validate the deposit return shape before accessing positional indices ```` # Getting Your API Key Source: https://docs.defindex.io/integration-guide/guides-and-tutorials/getting-api-key Before integrating with the DeFindex API you need an API key. You create it yourself in the DeFindex Console: no invitation, no waiting list, no approval step. *** ## Step 1: Open the Console 👉 [https://console.defindex.io/](https://console.defindex.io/) Create your account with an email and a password of at least 15 characters, and accept the terms of use. The console then emails you a 6-digit code: enter it to verify your email. Keys are created only for a verified email. If you already have an account, log in. Accounts created before sign-up asked for this code are already verified. *** ## Step 2: Create the Key In the console, open the **API Keys** section, give the key a name (where it will run, for example `prod-backend`) and click **Create API Key**. The key looks like `sk_1234567890abcdef...`, and it is the only credential your backend needs. Copy it when it is shown: the console shows the full key once, and after that only its prefix. > **An account can hold up to 10 keys.** Create one per service or environment, so you can stop one without touching the others. Creating a key never affects the keys you already have. > **Keep it secret.** The key carries your account's permissions. Store it in an environment variable, never commit it, and never ship it in client-side code. *** ## Step 3: Use the API Key in Requests Include the key as a Bearer token in the `Authorization` header: ```http theme={null} Authorization: Bearer ``` TypeScript example: ```typescript theme={null} const response = await fetch(`https://api.defindex.io/vault/${vaultAddress}/deposit`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${process.env.DEFINDEX_API_KEY}` }, body: JSON.stringify(params) }); ``` You can check the API is reachable before you even register: `GET /health` and `GET /vault/discover?network=mainnet` need no key. Everything else answers `401 Unauthorized` without a valid one. The JSON body carries a `code`: `MISSING_CREDENTIAL` when no key arrived, `INVALID_API_KEY` when the key was not accepted. Send the key exactly as above. An `x-api-key` header is ignored, so it answers `401` with `MISSING_CREDENTIAL`, and a key without the `Bearer ` prefix answers `403`. *** ## Key Lifetime and Rotation **The API key does not expire on a timer.** It works until you stop it from the **API Keys** section of the console: * **Disable** stops it until you enable it again. * **Revoke** stops it for good. A revoked key moves to the **Revoked** list, where you can delete it. If a script calls [`POST /api-keys/generate`](/api-reference/account/generate-api-key), each call replaces every key that route issued before, including any key made with the console's earlier **Generate API Key** button. Only keys created with **Create API Key** are left alone. If requests that used to work start answering `401` with `code: INVALID_API_KEY`, the key was revoked, disabled (the message then reads `API key disabled`) or replaced, not expired. Check its status in the console. To rotate a key without downtime, create a new one and deploy it next to the old one, check that the new key's **Last Used** moves, then revoke the old one. > **`refresh_token` is unrelated to your API key.** `/login` and `/refresh` issue short-lived JWT *access tokens*, which is how the console authenticates its own session. If you authenticate with an API key, you never call `/refresh`. *** ## Next Steps * [Getting Started with the API](/integration-guide/quickstart) * [Beginner Guide — Vault Deposit Example](/integration-guide/guides-and-tutorials/beginner-guide) * [Full API Reference](/api-reference) *** ## Need Help? If you run into issues, join our [Discord](https://discord.gg/aV5jHwmsaj) and ask in the developer channel. # Guides and Tutorials Source: https://docs.defindex.io/integration-guide/guides-and-tutorials/index # Privy Server Wallets Integration Source: https://docs.defindex.io/integration-guide/guides-and-tutorials/privy-server-wallets ## Overview This guide points to a reference repository that shows you how to integrate DeFindex vaults using **Privy server wallets** enabling fully automated, server-side deposits, withdrawals, and cross-chain bridging with **zero user interaction**. The pattern relies on Privy's **Authorization Key** (TEE-backed) to sign Stellar transactions from your backend, making it ideal for custodial products, bots, and programmatic yield strategies. ## Repository [**defindex-io/privy-defindex-guide**](https://github.com/defindex-io/privy-defindex-guide) ## What the Repository Covers | Topic | Description | | - | - | | Privy setup | App ID, TEE activation, Authorization Key generation | | Stellar wallet | Creation, XLM funding via Friendbot, USDC trustline | | EVM wallet | Base EVM wallet with `sendTransaction` | | Deposit | Full signing flow: XDR → hash → `rawSign` → broadcast | | Withdraw | Withdraw by amount or by shares (% redemption) | | Bridge | Base USDC → Stellar → Defindex vault via Sodax | | Gotchas | 9 documented edge cases with root causes and fixes | ## Architecture at a Glance ```md theme={null} Your Server (P-256 Authorization Key) │ signs every request ▼ Privy TEE ├── Stellar wallet (Tier 2) — rawSign only └── EVM wallet (Tier 3) — full sendTransaction Defindex API (api.defindex.io) ├── POST /vault/{addr}/deposit → unsigned Soroban XDR ├── POST /vault/{addr}/withdraw → unsigned Soroban XDR ├── POST /vault/{addr}/withdraw_shares → unsigned Soroban XDR └── POST /send → { txHash } ``` All vault operations follow the same signing loop: 1. Authenticated `POST` to Defindex API → receive unsigned XDR 2. Parse XDR → hash it 3. `privy.rawSign(walletId, { hash })` → Ed25519 signature 4. Attach `DecoratedSignature` to the envelope 5. `POST` signed XDR to `/send` ## Quick Start ```bash theme={null} git clone https://github.com/paltalabs/privy-defindex-guide cd privy-defindex-guide pnpm install cp .env.example .env # Fill in: PRIVY_APP_ID, PRIVY_APP_SECRET, PRIVY_AUTHORIZATION_PRIVATE_KEY, DEFINDEX_API_KEY ``` ```bash theme={null} pnpm example:deposit # Deposit into Defindex XLM vault (testnet) pnpm example:withdraw # Withdraw by amount (testnet) pnpm example:withdraw-shares # Withdraw by shares / percentage (testnet) pnpm example:bridge # Base USDC → Stellar → Defindex vault (mainnet) ``` ## Prerequisites * [Privy](https://privy.io) app with TEE enabled and an Authorization Key configured * Defindex API key — generate one at [console.defindex.io](https://console.defindex.io/) under **API Keys** ## Additional Resources * [Privy Documentation](https://docs.privy.io) * [Defindex API Reference](/api-reference) * [Sodax Bridge Documentation](https://docs.sodax.io) # Sponsored Transactions (Fee Bump) Source: https://docs.defindex.io/integration-guide/guides-and-tutorials/sponsored-transactions ## Introduction Sponsored transactions allow a **sponsor account** to pay Stellar transaction fees on behalf of another user. This is essential when working with **smart accounts** (Soroban contract-based accounts) that cannot pay fees themselves. Using the fee-bump pattern, you can build seamless user experiences where end users never need to hold XLM for gas. This guide walks you through implementing fee-bump deposits and withdrawals with the DeFindex API. ## Why Are Sponsored Transactions Needed? ### Smart Accounts and Transaction Fees On Stellar, there are two types of accounts: * **Native accounts** (`G...` addresses) — Standard Stellar accounts that hold XLM and can pay transaction fees. They also serve as the **source account** (sequence number provider) for transactions. * **Smart accounts** (`C...` addresses) — Soroban contract-based accounts. These accounts **cannot be the source account** of a transaction and **cannot pay transaction fees** because Stellar requires fees and sequence numbers from a native `G...` account. > - **Source** = always a native `G...` account (provides the sequence number). In a fee-bump transaction, the **sponsor** pays the fee, not the source account. > - **Caller (from)** = can be `G...` or `C...` (the account that authorizes the vault operation) When a DeFindex vault is operated by a smart account, the transaction will fail if no one covers the fee. ### The Fee-Bump Solution Stellar's **fee-bump transaction** wraps an existing (inner) transaction with an outer envelope that specifies a different fee-paying account: ``` ┌──────────────────────────────────────┐ │ Fee-Bump Transaction (outer) │ │ Fee Source: Sponsor (G...) │ │ │ │ ┌──────────────────────────────┐ │ │ │ Inner Transaction │ │ │ │ Source: Native account (G..)│ │ │ │ Caller/From: C... or G... │ │ │ │ Operations: deposit/ │ │ │ │ withdraw, etc. │ │ │ │ Signed by: Caller │ │ │ └──────────────────────────────┘ │ │ │ │ Signed by: Sponsor │ └──────────────────────────────────────┘ ``` The inner transaction's **source account** is always a native `G...` account (which provides the sequence number). The **caller** signs the inner transaction to authorize the vault operation. The **sponsor** wraps it in a fee-bump and signs the outer transaction to pay the fee. The network processes both as a single unit. ## Prerequisites * **`@stellar/stellar-sdk`** `^14.3.0` * **Two Stellar keypairs:** * **Sponsor** — A native `G...` account funded with XLM to pay fees * **Caller** — The account executing vault operations (can be `G...` or `C...`) * **DeFindex API key** (generate it at the [DeFindex Console](https://console.defindex.io/) under **API Keys**) ### Environment Configuration Create a `.env` file based on the following template: ```bash theme={null} # Network: testnet or mainnet NETWORK=testnet # Sponsor keypair secret (pays transaction fees) SPONSOR_SECRET=SXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX # Caller secret (signs the inner transaction; see note below) CALLER_SECRET=SXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX # Defindex API credentials DEFINDEX_API_KEY=your_api_key_here DEFINDEX_API_URL=https://api.defindex.io # Vault contract address on Stellar VAULT_ADDRESS=CXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX ``` > **Note on `CALLER_SECRET` and smart accounts:** > `CALLER_SECRET` expects a Stellar secret key (`S...`) for native `G...` accounts. If the caller is a **smart account** (`C...`), authorization comes from wallet interactions (Freighter, xBull, etc.), not a raw private key. In that scenario, present the unsigned XDR to the user's wallet for signing instead of using `Keypair.fromSecret(...)`. ## Deposit with Fee Bump ### Step 1: Initialize API Client and Keypairs ```typescript theme={null} import { Keypair, Networks, Transaction, TransactionBuilder, } from "@stellar/stellar-sdk"; import { config } from "dotenv"; config(); const network = process.env.NETWORK?.toLowerCase() || "testnet"; const isMainnet = network === "mainnet"; const stellarNetwork = isMainnet ? Networks.PUBLIC : Networks.TESTNET; const API_BASE = process.env.DEFINDEX_API_URL as string; const API_KEY = process.env.DEFINDEX_API_KEY as string; const sponsorKeypair = Keypair.fromSecret(process.env.SPONSOR_SECRET as string); // Assumes caller is a native G... account. For smart accounts (C...), use wallet signing instead. const callerKeypair = Keypair.fromSecret(process.env.CALLER_SECRET as string); // Lightweight helper for DeFindex API calls. Alternatively, you can use the @defindex/sdk package. async function api(path: string, options?: { method?: string; body?: unknown }): Promise { const separator = path.includes("?") ? "&" : "?"; const url = `${API_BASE}${path}${separator}network=${network}`; const res = await fetch(url, { method: options?.method ?? "GET", headers: { "Content-Type": "application/json", Authorization: `Bearer ${API_KEY}`, }, ...(options?.body ? { body: JSON.stringify(options.body) } : {}), }); if (!res.ok) { const errorBody = await res.text(); throw new Error(`API ${res.status}: ${errorBody}`); } return res.json() as Promise; } ``` ### Step 2: Get Unsigned Deposit Transaction > **API Reference:** [`POST /vault/{address}/deposit`](/api-reference/vaults/deposit) — `DepositDto` ```typescript theme={null} const vaultAddress = process.env.VAULT_ADDRESS as string; const depositResponse = await api<{ xdr: string }>( `/vault/${vaultAddress}/deposit`, { method: "POST", body: { amounts: [10000000], // Amount in stroops invest: true, // Auto-invest into strategies caller: callerKeypair.publicKey(), }, } ); ``` ### Step 3: Sign Inner Transaction with Caller ```typescript theme={null} const transaction = TransactionBuilder.fromXDR( depositResponse.xdr, stellarNetwork ) as Transaction; transaction.sign(callerKeypair); ``` ### Step 4: Create and Sign Fee-Bump with Sponsor ```typescript theme={null} const innerTxFee = parseInt(transaction.fee); const feeBumpTx = TransactionBuilder.buildFeeBumpTransaction( sponsorKeypair, innerTxFee.toString(), transaction, stellarNetwork ); feeBumpTx.sign(sponsorKeypair); ``` ### Step 5: Submit the Transaction > **API Reference:** [`POST /send`](/api-reference/transactions/send) — `SendXdrDto` ```typescript theme={null} const feeBumpXdr = feeBumpTx.toXDR(); const response = await api<{ txHash: string }>( "/send", { method: "POST", body: { xdr: feeBumpXdr } } ); console.log("Transaction hash:", response.txHash); ``` ## Withdraw with Fee Bump The withdrawal flow is the same pattern, but first queries the user's vault balance to determine how much of the underlying assets to withdraw. ### Step 1: Get Vault Balance > **API Reference:** [`GET /vault/{address}/balance`](/api-reference/vaults/balance) ```typescript theme={null} const balanceResponse = await api<{ dfTokens: number; underlyingBalance: number[] }>( `/vault/${vaultAddress}/balance?from=${callerKeypair.publicKey()}` ); const amountsToWithdraw = balanceResponse.underlyingBalance; ``` ### Step 2: Get Unsigned Withdrawal Transaction > **API Reference:** [`POST /vault/{address}/withdraw`](/api-reference/vaults/withdraw) — `WithdrawDto` ```typescript theme={null} const withdrawResponse = await api<{ xdr: string }>( `/vault/${vaultAddress}/withdraw`, { method: "POST", body: { amounts: amountsToWithdraw, caller: callerKeypair.publicKey(), slippageBps: 100, // Optional: max slippage in basis points (100 = 1%) }, } ); ``` ### Step 3: Sign, Wrap, and Submit The signing and fee-bump steps are identical to the deposit flow: ```typescript theme={null} // Sign inner transaction with caller const transaction = TransactionBuilder.fromXDR( withdrawResponse.xdr, stellarNetwork ) as Transaction; transaction.sign(callerKeypair); // Create fee-bump with sponsor const innerTxFee = parseInt(transaction.fee); const feeBumpTx = TransactionBuilder.buildFeeBumpTransaction( sponsorKeypair, innerTxFee.toString(), transaction, stellarNetwork ); feeBumpTx.sign(sponsorKeypair); // Submit const response = await api<{ txHash: string }>( "/send", { method: "POST", body: { xdr: feeBumpTx.toXDR() } } ); console.log("Transaction hash:", response.txHash); ``` ## Fee Considerations * `buildFeeBumpTransaction` takes a **per-operation base fee**, not a total fee. The SDK internally multiplies by `(numOperations + 1)` to compute the total fee-bump fee ([CAP-0015 rule](https://github.com/stellar/stellar-protocol/blob/master/core/cap-0015.md)). * For a typical Soroban transaction with 1 operation, passing `parseInt(transaction.fee)` as the base fee produces a **total** fee-bump fee of `2 × innerFee` (since `1 op + 1 = 2`). This satisfies the protocol's fee-rate check because the per-operation rate equals the inner transaction's rate. * The DeFindex API builds the inner transaction with a simulated resource fee and a correct inclusion fee. Passing `parseInt(transaction.fee)` as the base fee ensures you meet the required minimum. * To **increase priority** during network congestion, pass a higher base fee: ```typescript theme={null} const feeBumpTx = TransactionBuilder.buildFeeBumpTransaction( sponsorKeypair, (innerTxFee * 2).toString(), // 2× base fee → 4× total fee (for a 1-op tx) for higher priority transaction, stellarNetwork ); ``` ## Common Issues | Issue | Cause | Solution | | - | - | - | | `tx_insufficient_fee` | Fee-bump per-operation fee rate is lower than the inner transaction's rate | Ensure the base fee passed to `buildFeeBumpTransaction` is ≥ `parseInt(transaction.fee)`. The SDK handles the `(numOps + 1)` multiplication internally | | `tx_bad_auth` | Inner transaction not signed by caller | Ensure `transaction.sign(callerKeypair)` is called before building the fee-bump | | Wrong signing order | Fee-bump created before signing inner tx | Always sign the inner transaction first, then build the fee-bump | | `429 Too Many Requests` | API rate limit exceeded | Implement exponential backoff (see [Troubleshooting](/integration-guide/troubleshooting#rate-limiting)) | | `tx_bad_seq` | Stale sequence number | Re-fetch the unsigned transaction from the API and retry. Note that Soroban resource estimates (footprint, CPU/memory limits) are also ledger-specific, so simply adjusting the sequence number on a stale transaction is not enough — you must request a fresh XDR | | `tx_too_late` | Transaction timebounds expired before submission | The XDR was held too long. Re-fetch a fresh unsigned transaction from the API and sign/submit promptly | ## Production Notes * **Channel accounts for concurrent sponsors:** If the sponsor account submits multiple fee-bump transactions in parallel, sequence-number collisions will cause failures. Use [channel accounts](https://developers.stellar.org/docs/encyclopedia/channel-accounts). a pool of funded `G...` accounts — so each concurrent submission uses its own sequence number. * **XDR verification before signing:** In production, the sponsor should decode and inspect the inner transaction XDR before signing. Verify that the operations, amounts, and destination contracts match expected values. Never blindly sign arbitrary XDRs. ## Complete Example Repository A fully working example with deposit and withdraw scripts is available at: [**paltalabs/examples/defindex-sdk-deposit-withdraw-fee-bump**](https://github.com/paltalabs/examples/tree/main/defindex-sdk-deposit-withdraw-fee-bump) To run it: ```bash theme={null} git clone https://github.com/paltalabs/examples.git cd examples/defindex-sdk-deposit-withdraw-fee-bump npm install cp .env.example .env # Edit .env with your keys and vault address npm run deposit # Run deposit example npm run withdraw # Run withdraw example ``` ## Additional Resources * [Stellar Fee-Bump Transactions](https://developers.stellar.org/docs/build/guides/transactions/fee-bump-transactions) * [Deposit](/integration-guide/vault-operations/deposit) * [Withdraw](/integration-guide/vault-operations/withdraw) * [DeFindex API reference](/api-reference) # Blend to DeFindex Source: https://docs.defindex.io/integration-guide/migrating-positions/blend-to-defindex Moves a user's Blend USDC lending position into a DeFindex vault. Mainnet only. Two steps, and the first is optional: 1. **(Optional) Recover BLND rewards.** If your users have accrued BLND emissions on Blend and you want to sweep them into a wallet before migrating, call `POST /migration/claim-blnd` first. If you do not care about the BLND rewards, skip this step. 2. **Migrate the USDC position.** Call `POST /migration/blend-to-defindex` to atomically withdraw the user's full Blend USDC position and deposit it into a DeFindex vault. Each call returns one XDR. Have the user sign it, submit it, wait for confirmation, then move on to the next step. ## `POST /migration/claim-blnd` Claims the user's first available BLND claimable balance (the standard place Blend leaves emission rewards) and forwards the BLND to a destination wallet. The returned transaction wraps the claim and payment between an open-trustline and a close-trustline operation, so the user does not need to keep a permanent BLND trustline on their account. ```json theme={null} { "from": "G...", "destination": "G..." } ``` | Field | Type | Required | Notes | | - | - | - | - | | `from` | string | yes | User's Stellar public key. This account must sign the returned XDR. | | `destination` | string | no | Wallet that receives the claimed BLND. If omitted, the BLND is sent to a DeFindex-operated fallback address, so always pass the wallet you want the rewards in. | Response: ```json theme={null} { "xdr": "AAAAAg...", "balanceId": "0000000071f...", "amount": "1234.5678901", "destination": "G..." } ``` `amount` is the BLND being forwarded, formatted with 7 decimal places. Surface it to the user before they sign. One thing to watch: this XDR is a **classic Stellar transaction**, not a Soroban one. Submit it directly to Horizon; the `POST /send` endpoint will not accept it. Errors: `400` when an address is invalid, `404` when the user has no BLND claimable balance or the account does not exist. ## `POST /migration/blend-to-defindex` Atomically withdraws the user's **full** Blend USDC position and deposits the proceeds into a DeFindex vault, in a single signed transaction. The endpoint reads the user's Blend position on-chain and computes the exact withdrawal amount on the server side, handling the small interest accrual that happens between simulation and submission so the user always receives at least what was simulated. Your client only passes two addresses: ```json theme={null} { "from": "G...", "vaultAddress": "C..." } ``` | Field | Type | Required | Notes | | - | - | - | - | | `from` | string | yes | User's Stellar public key. This account must sign the returned XDR. | | `vaultAddress` | string | yes | DeFindex vault contract address that receives the deposit. | Response: ```json theme={null} { "xdr": "AAAAAg...", "simulationResponse": [ ], "functionName": "exec", "operationXDR": "AAAAEA...", "isSmartWallet": false } ``` `simulationResponse` carries the decoded return values of the simulated transaction, useful for previewing the result to the user before they sign. `operationXDR` is the raw operation, in case you need to rebuild the transaction with a different fee or timeout. Sign `xdr` and submit it through your own RPC or `POST /send`. Errors: `400` when an address is invalid or the user holds both a supply and a collateral position at once (contact us if you hit this for a real user), `404` when the user has no Blend USDC position to migrate. # DeFindex to DeFindex Source: https://docs.defindex.io/integration-guide/migrating-positions/defindex-to-defindex ## `POST /migration/defindex-to-defindex` Moves a user's **entire** position from one DeFindex vault into another. There is no partial migration: the user's full share balance in the source vault is withdrawn. The target vault must hold the same assets, in the same order, as the source vault; the endpoint verifies this before building anything, because the deposit matches amounts to assets by position. Works on both networks. The `network` query parameter accepts `mainnet` or `testnet` and defaults to `mainnet`. ```http theme={null} POST /migration/defindex-to-defindex?network=mainnet ``` ```json theme={null} { "from": "G...", "fromVault": "C...", "toVault": "C...", "slippageBps": 10 } ``` | Field | Type | Required | Notes | | - | - | - | - | | `from` | string | yes | User's Stellar public key. Holds the source vault shares and signs the XDR. | | `fromVault` | string | yes | Source vault. The user's entire share balance here is withdrawn. | | `toVault` | string | yes | Target vault. Must hold the same assets, in the same order, as `fromVault`. | | `slippageBps` | number | no | Buffer applied to the proceeds before depositing. Defaults to `10` (0.1%). | Response: ```json theme={null} { "xdr": "AAAAAg...", "simulationResponse": [ ], "functionName": "exec", "operationXDR": "AAAAEA...", "isSmartWallet": false } ``` Sign `xdr` and submit it through your own RPC or `POST /send`. After confirmation the user holds shares in the target vault. ## About `slippageBps` The transaction deposits a **floor**, not the exact amount withdrawn. The deposit needs a fixed amount decided when the transaction is built, but the value of a vault share can move slightly between the moment the transaction is simulated and the moment the user submits it. If the deposit demanded the exact simulated amount and the value dipped in between, the whole transaction would revert. So the amount is shrunk by `slippageBps` and that lower number is used for both legs. The trade-off: * **The migration is resilient**: small share-price movements no longer revert it. * **A sliver stays behind** in the user's wallet, roughly `slippageBps` of the position. At the default 10 bps that is 0.1%. Raise it if you see migrations reverting; lower it, down to `0`, if you want zero dust and are willing to retry on failure. Errors: `400` when an address is invalid, `fromVault` equals `toVault`, the two vaults hold different assets, or the position is so small it rounds to zero once the buffer is applied; `404` when the user holds no shares in `fromVault`. # Migrating Positions Source: https://docs.defindex.io/integration-guide/migrating-positions/index The migration endpoints move a user's entire position into a DeFindex vault in **one atomic transaction**. The withdrawal from the old position and the deposit into the new vault travel inside the same transaction, so the migration either fully succeeds or fully reverts: there is no intermediate state where the user is left holding loose funds between the two steps, and nothing for your application to clean up after a failure. Every endpoint returns an **unsigned transaction XDR**. Your application has the user sign it, then submits it either directly to the Stellar network through your own RPC connection, or through the API's `POST /send` endpoint. Authentication is the standard `Authorization: Bearer ` header used across the API. There are two migrations: * [**Blend to DeFindex**](/integration-guide/migrating-positions/blend-to-defindex) (mainnet only): move a user's Blend USDC lending position into a DeFindex vault, with an optional first step to recover their BLND rewards. * [**DeFindex to DeFindex**](/integration-guide/migrating-positions/defindex-to-defindex) (mainnet or testnet): move a user's full position between two vaults, for example when retiring a vault or moving users onto one with a different strategy set. # Quickstart Source: https://docs.defindex.io/integration-guide/quickstart A working deposit, in three curl commands. You need a Console account and a Stellar account that can sign. Everything below runs on mainnet; swap in `?network=testnet` to try it on the [Sandbox](/integration-guide/sandbox) first. [Integration walkthrough](https://www.youtube.com/embed/gz6GU5kAUXY?si=54lqva3t6lzKjvdH\&start=145) ## 1. Get an API key and a vault Open the [Console](https://console.defindex.io), create an account and verify your email, go to **API Keys** and create one. It looks like `sk_...` and it is the only credential your backend needs. You can hold several keys, one per service, and revoke any of them without touching the others. Create your vault in the same place, or point at one that already exists. Either way you end up with a vault address. The longer walkthrough is in [Getting your API key](/integration-guide/guides-and-tutorials/getting-api-key). ## 2. Build a deposit The API returns an unsigned transaction for the user. Amounts are in the asset's smallest unit, 7 decimals for USDC and XLM. ```bash theme={null} curl -X POST "https://api.defindex.io/vault/VAULT_ADDRESS/deposit?network=mainnet" \ -H "Authorization: Bearer sk_..." \ -H "Content-Type: application/json" \ -d '{ "amounts": [10000000], "caller": "GUSER...", "invest": true }' ``` The response carries `xdr`, the transaction to sign. ## 3. Sign and send Sign `xdr` with the user's key, in your wallet stack or with the Stellar SDK, and send it back: ```bash theme={null} curl -X POST "https://api.defindex.io/send?network=mainnet" \ -H "Authorization: Bearer sk_..." \ -H "Content-Type: application/json" \ -d '{ "xdr": "SIGNED_XDR" }' ``` Then read the balance: ```bash theme={null} curl "https://api.defindex.io/vault/VAULT_ADDRESS/balance?from=GUSER...&network=mainnet" \ -H "Authorization: Bearer sk_..." ``` `underlyingBalance` is what the user holds, in the vault's asset. Withdraw is the same flow against `/withdraw`. ## The same thing in TypeScript One client class covers every call. `POST /send` sits at the API root rather than under a vault path, which is the only shape that differs. ```typescript theme={null} class ApiClient { private readonly apiUrl = "api.defindex.io"; constructor(private readonly apiKey: string) {} private headers() { return { 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.apiKey}` }; } async postData(endpoint: string, vaultAddress: string, params: Record) { const res = await fetch(`https://${this.apiUrl}/vault/${vaultAddress}/${endpoint}`, { method: 'POST', headers: this.headers(), body: JSON.stringify(params) }); return res.json(); } async getData(endpoint: string, vaultAddress: string, params?: Record) { const qs = params ? `?${new URLSearchParams(params)}` : ''; const res = await fetch(`https://${this.apiUrl}/vault/${vaultAddress}/${endpoint}${qs}`, { method: 'GET', headers: this.headers() }); return res.json(); } async send(signedXdr: string) { const res = await fetch(`https://${this.apiUrl}/send`, { method: 'POST', headers: this.headers(), body: JSON.stringify({ xdr: signedXdr }) }); return res.json(); } } ``` ## Next * [Vault Operations](/integration-guide/vault-operations/index): deposit, withdraw, balance and APY, one page each. * [API reference](/api-reference): every route and every parameter. * [Fees and revenue](/intro/fees): set your fee and see what you keep. # Sandbox Source: https://docs.defindex.io/integration-guide/sandbox Testnet, where the money is fake and everything else is the same. Everything in these docs runs on Stellar testnet with `?network=testnet`. Same API, same contracts, faucet money. ## What you need | | Testnet | | - | - | | API | `https://api.defindex.io`, with `?network=testnet` on every call | | XLM for fees | [Friendbot](https://laboratory.stellar.org/#account-creator?network=test) | | BlendUSDC to deposit | The faucet at [testnet.blend.capital](https://testnet.blend.capital), with a Freighter wallet set to Testnet | | Contract addresses | [testnet.contracts.json](https://github.com/defindex-io/stellar-contracts/blob/main/public/testnet.contracts.json) | | RPC | `https://soroban-testnet.stellar.org` | Your API key from the [Console](https://console.defindex.io) works on both networks. ## What differs from mainnet * Assets are test tokens. BlendUSDC on testnet is not Circle USDC. * Stellar resets testnet periodically and every address stops working when it does. The next scheduled reset is December 16, 2026. If an address fails, ask on [Discord](https://discord.gg/aV5jHwmsaj). * Stable APY runs on mainnet only. ## Next * [Quickstart](/integration-guide/quickstart), with `network=testnet`. * [Create a Vault using the API](/integration-guide/creating-a-defindex-vault/using-the-api): a full testnet example in TypeScript. # Stable APY endpoints Source: https://docs.defindex.io/integration-guide/stable-apy The stabilizer API, route by route. The reference for the stabilizer. For what it does and when to use it, read [Stable APY](/products/stable-apy) first. All routes live under `https://api.defindex.io/stabilizer/{vaultAddress}` and take an optional `?network=mainnet` query parameter. Authentication is the standard `Authorization: Bearer ` header used across the API. > [!NOTE] > > Mainnet only, and enabled per account: every route below returns `403 Forbidden` until the feature is switched on for your API key. [Contact us on Discord](https://discord.gg/aV5jHwmsaj) to enable it. ## The response shape Every write endpoint returns an unsigned transaction for the `caller` you pass in the body: ```json theme={null} { "xdr": "AAAAAg...", "simulationResponse": { }, "functionName": "register_vault", "operationXDR": "AAAAEA...", "isSmartWallet": false } ``` Sign `xdr` with the caller's key and submit it, either through your own RPC connection or through the API's `POST /send` endpoint, the same flow as any [Vault Operation](/integration-guide/vault-operations/index). Smart wallet callers (C addresses) cannot sign a prebuilt transaction, so for them `xdr` comes back `null` and `isSmartWallet` is `true`. Build your own transaction around `operationXDR` instead. ## `GET /stabilizer/{vaultAddress}/status` Read only snapshot of the vault's stabilizer state: ```json theme={null} { "registered": true, "managedByStabilizer": true, "config": { "adminAddress": "G...", "targetApyBps": 800, "minFeeBps": 0, "maxFeeBps": 2000 }, "campaign": { "active": true, "asset": "C...", "totalDeposited": "1000000000", "totalBoosted": "42000000", "totalWithdrawn": "0", "available": "958000000", "lastBoostedAt": 1756400000 }, "currentFeeBps": 1250 } ``` `config` is `null` when the vault is not registered. `campaign` is `null` when the vault has no boost campaign. The two are independent: a vault can be registered without a campaign, and the other way around. Campaign amounts are in stroops of the campaign asset, and `lastBoostedAt` is unix seconds, `0` meaning never. ## `POST /stabilizer/{vaultAddress}/register` ```json theme={null} { "caller": "G...", "targetApyBps": 800, "minFeeBps": 0, "maxFeeBps": 2000 } ``` `caller` must be the vault's **current Manager** and becomes the vault's stabilizer admin: the address that controls every setting below and the only one that can exit. The returned transaction both registers the vault and hands the Manager role to the stabilizer contract, so one signature covers the whole handoff. All rates are basis points: `10000` is 100%, `800` is 8%. `minFeeBps` must be less than or equal to `maxFeeBps`. `minFeeBps` is the floor the fee can never go below, including while a boost campaign is running. It is a commercial decision more than a technical one: see [what a boost costs](/products/stable-apy#what-a-boost-costs). ## `POST /stabilizer/{vaultAddress}/target-apy` ```json theme={null} { "caller": "G...", "targetApyBps": 650 } ``` Changes the target. `caller` must be the vault's stabilizer admin. ## `POST /stabilizer/{vaultAddress}/fee-bounds` ```json theme={null} { "caller": "G...", "minFeeBps": 0, "maxFeeBps": 1500 } ``` Changes the fee range the stabilizer may use. `caller` must be the vault's stabilizer admin, and `minFeeBps` must be less than or equal to `maxFeeBps`. ## `POST /stabilizer/{vaultAddress}/exit` ```json theme={null} { "caller": "G..." } ``` Unregisters the vault and returns the Manager role to the stabilizer admin. `caller` must be the vault's stabilizer admin. ## `POST /stabilizer/{vaultAddress}/boost/deposit` ```json theme={null} { "caller": "G...", "amount": "1000000000" } ``` Funds the vault's boost campaign. `amount` is stroops of the campaign asset, as a string. Anyone may fund an active campaign, not just the admin. Returns `404` if the vault has no campaign registered and `400` if the campaign is inactive. ## Errors | Status | When | | - | - | | `400` | The stabilizer is not available on the requested network, `minFeeBps` exceeds `maxFeeBps`, `amount` is not a positive integer string, or the boost campaign is inactive. | | `403` | The feature is not enabled for your API key, or `caller` is not the vault's Manager (register) or stabilizer admin (all other writes). | | `404` | The vault is not registered with the stabilizer, or it has no boost campaign. | # Troubleshooting Source: https://docs.defindex.io/integration-guide/troubleshooting This guide provides solutions and explanations for common issues encountered when using the DeFindex protocol. It covers API errors, environment setup, contract error codes, transaction failures, and frequently asked questions. ## Table of Contents * [API](/integration-guide/troubleshooting#api) * [API Error Reference](/integration-guide/troubleshooting#api-error-reference) * [API Rate Limits](/integration-guide/troubleshooting#rate-limiting) * [Environment & Configuration](/integration-guide/troubleshooting#environment--configuration) * [Step-by-Step Debugging Guide](/integration-guide/troubleshooting#step-by-step-debugging-guide) * [Smart Contracts](/integration-guide/troubleshooting#smart-contracts) * [Error Log Debugging Example](/integration-guide/troubleshooting#error-log-debbugging-example) * [Common Contract Errors](/integration-guide/troubleshooting#common-contract-errors) * [Deposit with `invest: true` stays idle](/integration-guide/troubleshooting#deposit-with-invest-true-stays-idle) * [Withdrawing All — Dust Left Behind](/integration-guide/troubleshooting#withdrawing-all--dust-left-behind) * [Soroban Transaction Errors](/integration-guide/troubleshooting#soroban-transaction-errors) * [Frequently Asked Questions (FAQ)](/integration-guide/troubleshooting#frequently-asked-questions-faq) * [Additional Resources](/integration-guide/troubleshooting#additional-resources) ## API ### API Error Reference HTTP status codes returned by the DeFindex API: | Status | Error | Common Causes | Solution | | - | - | - | - | | 400 | Bad Request | Invalid address format, wrong amounts length, missing parameters, slippage out of range, contract simulation failure | Check request body against API docs; for simulation failures inspect the `errorCode` field for the contract error code | | 401 | Unauthorized | No API key (`code: MISSING_CREDENTIAL`, also when it was sent in an `x-api-key` header), or a key that was revoked, disabled or replaced (`code: INVALID_API_KEY`). The response carries a `WWW-Authenticate` header and a `registerUrl` | Send `Authorization: Bearer ` with a key that shows as active in the [console](https://console.defindex.io/). Branch on `code`, not on `message` | | 403 | Forbidden | A valid key on a route not enabled for your account (for example [Stable APY](/integration-guide/stable-apy)), a key sent without the `Bearer ` prefix, or an expired console session (JWT access token) | Check the key is sent as `Authorization: Bearer `. For a console session, call `/refresh` with your `refresh_token` or log in again | | 404 | Not Found | Vault address not found, account has no transactions | Verify the address and network (testnet or mainnet) | | 409 | Conflict | Duplicate email on registration | Use a different email address | | 429 | Too Many Requests | Rate limit exceeded | Implement backoff (see [API Rate Limits](/integration-guide/troubleshooting#rate-limiting)); check `retryAfter` in response | | 503 | Service Unavailable | Stellar network unreachable, external service failure | Retry after a delay; check Stellar network status | ### API Rate Limits The DeFindex API uses a rate limiter with a 5 minute window. Limits are applied per API key (authenticated requests) or per IP address (unauthenticated requests). #### Rate Limit Tiers | Tier | Burst Capacity | Sustained Rate | | - | - | - | | Free | 5 requests | 1 req/s | | Starter | 20 requests | 10 req/s | | Professional | 100 requests | 50 req/s | | Business | 200 requests | 100 req/s | Contact PaltaLabs🥑 team on [discord](https://discord.gg/aV5jHwmsaj) to upgrade tier. #### Response Headers Every API response includes rate limit headers: | Header | Description | | - | - | | `X-RateLimit-Limit` | Maximum requests allowed in the current window | | `X-RateLimit-Remaining` | Requests remaining in the current window | | `X-RateLimit-Reset` | Unix timestamp when the window resets | > **Tip:** Use the `GET /rate-limits/tiers` endpoint to retrieve the current rate limit configuration for your API key. #### Handling 429 Responses When you exceed the rate limit, the API returns **429 (Too Many Requests)**. Use exponential backoff to handle this: ```typescript theme={null} async function withRateLimit( fn: () => Promise, maxRetries: number = 5, initialDelay: number = 1000 ): Promise { let lastError: any; for (let attempt = 0; attempt <= maxRetries; attempt++) { try { return await fn(); } catch (error: any) { lastError = error; if (error?.statusCode === 429 || error?.error === "Too Many Requests") { const retryAfter = error?.retryAfter || 1; const delayMs = Math.max( retryAfter * 1000, initialDelay * Math.pow(2, attempt) ); if (attempt < maxRetries) { await new Promise((resolve) => setTimeout(resolve, delayMs)); continue; } } throw error; } } throw lastError; } ``` Usage example: ```typescript theme={null} const depositResponse = await withRateLimit(() => defindexSdk.depositToVault(vaultAddress, depositData, supportedNetwork) ); ``` ## Environment & Configuration ### Step-by-Step Debugging Guide #### 1. Check Environment Variables * Ensure all required environment variables (e.g., `MAINNET_RPC_URL`) are set correctly. * Example (.env): ```dotenv theme={null} MAINNET_RPC_URL=your_rpc_url ``` #### 2. Validate Network and Contract Deployment * Confirm you are connected to the correct network (testnet/mainnet). * Verify the contract address is correct and the contract is deployed. #### 3. Simulate Transactions Before Sending * Use the SDK's simulation methods to check for errors before submitting transactions. * Review simulation results for error codes or failed preconditions. #### 4. Handle Transaction Failures * If a transaction fails, inspect the error code returned. * Refer to the tables in this page to interpret the error and apply the suggested fix. #### 5. Check Parameter Types and Lengths * Ensure all parameters (amounts, addresses, etc.) are of the correct type and length. * For multi-asset vaults, input arrays must match the number of assets. #### 6. Review Contract and SDK Versions * Make sure you are using compatible versions of the SDK and smart contracts. #### 7. Debug XDR manually * Debug XDR transaction in [Stellar Lab](https://lab.stellar.org) ## Smart Contracts ### Error Log Debbugging Example Consider the following error log from a `withdraw` transaction: ``` Event log (newest first): 0: [Diagnostic Event] contract:CBDZYJVQJQT7QJ7ZTMGNGZ7RR3DF32LERLZ26A2HLW5FNJ4OOZCLI3OG, topics:[error, Error(Contract, #160)], data:"escalating error to VM trap from failed host function call: fail_with_error" 1: [Diagnostic Event] contract:CBDZYJVQJQT7QJ7ZTMGNGZ7RR3DF32LERLZ26A2HLW5FNJ4OOZCLI3OG, topics:[error, Error(Contract, #160)], data:["failing with contract error", 160] 2: [Contract Event] contract:CBDZYJVQJQT7QJ7ZTMGNGZ7RR3DF32LERLZ26A2HLW5FNJ4OOZCLI3OG, topics:[burn, GBI6SIGPSKXTBLXGSAFT2TN5DYFBHIJXKO7IGGQTR7DKO2ANWILGXIDA], data:9999563 11: [Diagnostic Event] topics:[fn_call, CBDZYJVQJQT7QJ7ZTMGNGZ7RR3DF32LERLZ26A2HLW5FNJ4OOZCLI3OG, withdraw], data:[9999563, [10000065], GBI6SIGPSKXTBLXGSAFT2TN5DYFBHIJXKO7IGGQTR7DKO2ANWILGXIDA] ``` **Breakdown:** 1. **Identify the Error:** * Events `0` and `1` indicate the error: `Error(Contract, #160)`. * Error code: `160` (InsufficientOutputAmount) 2. **Understand the Context:** * Event `0`: The contract explicitly triggered an error. * Event `1`: Confirms the contract error code is 160. 3. **Determine Function Arguments:** * Event `11` shows the `withdraw` function call and its arguments: * `9999563`: `withdraw_shares` (number of shares to burn) * `[10000065]`: `min_amounts_out` (minimum expected output amount) * `GBI6SIGPSKXTBLXGSAFT2TN5DYFBHIJXKO7IGGQTR7DKO2ANWILGXIDA`: `to` (recipient address) 4. **Interpret the Error in Context:** * The `withdraw` transaction failed because the vault could not provide at least 10000065 stroops of the underlying asset when burning 9999563 shares. ### Common Contract Errors The DeFindex contracts return specific error codes when a transaction fails. Below is a comprehensive reference grouped by contract and category. ### Vault Errors #### Initialization Errors (100–108) | Code | Name | Cause | Solution/Tip | | - | - | - | - | | 100 | NotInitialized | Vault has not been initialized | Call the vault's `initialize` function before any other operation | | 101 | InvalidRatio | Asset allocation ratios are invalid (e.g., don't sum to expected total) | Ensure allocation ratios are valid and sum correctly | | 102 | StrategyDoesNotSupportAsset | A strategy was assigned an asset it cannot handle | Verify the strategy supports the asset before assigning | | 103 | NoAssetAllocation | No asset allocation was provided during initialization | Provide at least one asset allocation | | 104 | RolesIncomplete | Required roles were not fully assigned | Assign all required roles (manager, emergency manager, etc.) | | 105 | MetadataIncomplete | Vault metadata (name, symbol, etc.) is missing or incomplete | Provide all required metadata fields | | 106 | MaximumFeeExceeded | The fee set exceeds the maximum allowed | Lower the fee to 9,000 bps (90%) or less | | 107 | DuplicatedAsset | The same asset was provided more than once | Remove duplicate assets from the allocation | | 108 | DuplicatedStrategy | The same strategy was provided more than once | Remove duplicate strategies from the allocation | #### Validation Errors (110–129) | Code | Name | Cause | Solution/Tip | | - | - | - | - | | 110 | AmountNotAllowed | The provided amount is not allowed (e.g., zero or negative) | Check that all amounts are positive and within allowed limits | | 111 | InsufficientBalance | User does not have enough balance for the operation | Verify the user's token balance before submitting | | 112 | WrongAmountsLength | The number of amounts does not match the number of assets | Ensure your input arrays match the vault's asset count | | 113 | WrongLockedFees | Locked fees value is incorrect | Verify the locked fees parameter | | 114 | InsufficientManagedFunds | The vault does not have enough managed funds | Check vault TVL before attempting the operation | | 115 | MissingInstructionData | Required instruction data is missing | Verify all required parameters are provided for the operation | | 116 | UnsupportedAsset | The provided asset is not supported by the vault | Use only assets that the vault was configured with | | 117 | InsufficientAmount | The amount provided is too small | Increase the amount to meet the minimum requirement | | 118 | NoOptimalAmounts | Could not calculate optimal deposit amounts | This is an internal error; check vault state and asset ratios | | 119 | WrongInvestmentLength | The investment allocation array length is incorrect | Check that investment allocations match the number of strategies/assets | | 122 | WrongAssetAddress | The provided asset address does not match expected | Verify the asset contract address is correct | | 123 | WrongStrategiesLength | The strategies array length does not match expected | Ensure the strategies array length matches the vault configuration | | 124 | AmountOverTotalSupply | The requested amount exceeds the total supply of shares | Reduce the amount to at most the total supply | | 125 | NoInstructions | No instructions were provided for the operation | Provide the required instructions for the operation | | 126 | NotUpgradable | The vault contract is not upgradable | This vault was deployed as non-upgradable; deploy a new vault if needed | | 128 | UnwindMoreThanAvailable | Attempting to unwind more than is available in the strategy | Reduce the unwind amount or check available strategy balance | | 129 | InsufficientFeesToRelease | Not enough accrued fees to release | Wait for more fees to accumulate before releasing | #### Arithmetic Errors (120–127) | Code | Name | Cause | Solution/Tip | | - | - | - | - | | 120 | ArithmeticError | A general arithmetic error occurred | Check for very large or very small values that may cause overflow/underflow | | 121 | Overflow | An arithmetic overflow occurred | Reduce input values to prevent overflow | | 127 | Underflow | An arithmetic underflow occurred | Ensure values are large enough to avoid underflow | #### Authorization Errors (130–131) | Code | Name | Cause | Solution/Tip | | - | - | - | - | | 130 | Unauthorized | The caller is not authorized to perform this action | Ensure the caller has the required role (manager, emergency manager, etc.) | | 131 | RoleNotFound | The specified role does not exist | Check available roles in the vault configuration | #### Strategy Operation Errors (140–144) | Code | Name | Cause | Solution/Tip | | - | - | - | - | | 140 | StrategyNotFound | The specified strategy was not found in the vault | Verify the strategy address is registered with the vault | | 141 | StrategyPausedOrNotFound | The strategy is paused or does not exist | Check strategy status; if paused, contact the vault manager | | 142 | StrategyWithdrawError | An error occurred while withdrawing from a strategy | Check the strategy's state and available balance | | 143 | StrategyInvestError | An error occurred while investing into a strategy | Verify the investment amount and strategy availability | | 144 | StrategyPaused | The strategy is currently paused | Wait for the strategy to be unpaused or contact the vault manager | #### Asset Errors (150–151) | Code | Name | Cause | Solution/Tip | | - | - | - | - | | 150 | AssetNotFound | The specified asset was not found in the vault | Verify the asset address is correct and registered with the vault | | 151 | NoAssetsProvided | No assets were provided for the operation | Provide at least one asset | #### Input Errors (160–162) | Code | Name | Cause | Solution/Tip | | - | - | - | - | | 160 | InsufficientOutputAmount | The output amount is less than the required minimum | Lower your minimums or check vault liquidity before retrying | | 161 | ExcessiveInputAmount | The input amount exceeds allowed limits | Reduce the input amount to within allowed limits | | 162 | InvalidFeeBps | The fee basis points value is invalid | Provide a valid fee in basis points (0–9000) | #### External / Swap Errors (190–202) | Code | Name | Cause | Solution/Tip | | - | - | - | - | | 190 | LibrarySortIdenticalTokens | Soroswap library received two identical token addresses | Ensure the two tokens in the swap are different | | 200 | SoroswapRouterError | An error occurred in the Soroswap router | Check the Soroswap router status and input parameters | | 201 | SwapExactInError | The exact-input swap failed | Verify swap parameters (token addresses, amounts, deadline) | | 202 | SwapExactOutError | The exact-output swap failed | Verify swap parameters (token addresses, amounts, deadline) | ### Factory Errors | Code | Name | Cause | Solution/Tip | | - | - | - | - | | 401 | NotInitialized | The factory contract has not been initialized | Call `initialize` on the factory before creating vaults | | 404 | AssetLengthMismatch | The number of assets does not match the expected length | Ensure all asset arrays have consistent lengths | | 405 | IndexDoesNotExist | The requested vault index does not exist | Verify the vault index; use the factory to list available vaults | | 406 | FeeTooHigh | The specified fee exceeds the maximum allowed by the factory | Reduce the fee to within the factory's allowed range | ### Strategy Errors #### Validation Errors (401–418) | Code | Name | Cause | Solution/Tip | | - | - | - | - | | 401 | NotInitialized | The strategy contract has not been initialized | Call `initialize` on the strategy before use | | 410 | NegativeNotAllowed | A negative value was provided where only positive is allowed | Ensure all amounts are non-negative | | 411 | InvalidArgument | An invalid argument was provided | Check all function arguments against expected types and ranges | | 412 | InsufficientBalance | The strategy does not have enough balance | Verify the strategy's balance before withdrawing | | 413 | UnderflowOverflow | An arithmetic underflow or overflow occurred | Reduce input values to prevent arithmetic errors | | 414 | ArithmeticError | A general arithmetic error occurred | Check for edge cases in input values | | 415 | DivisionByZero | A division by zero was attempted | Ensure divisor values are non-zero | | 416 | InvalidSharesMinted | The calculated shares to mint are invalid (zero or negative) | Check that the deposit amount is large enough to produce valid shares | | 417 | OnlyPositiveAmountAllowed | The amount must be strictly positive | Provide a positive (non-zero) amount | | 418 | NotAuthorized | The caller is not authorized | Ensure the caller has permission (typically the vault contract) | #### Protocol Errors (420–423) | Code | Name | Cause | Solution/Tip | | - | - | - | - | | 420 | ProtocolAddressNotFound | The external protocol address was not found | Verify the protocol address is correctly configured in the strategy | | 421 | DeadlineExpired | The transaction deadline has passed | Resubmit the transaction with a fresh deadline | | 422 | ExternalError | An error occurred in an external protocol call | Check the external protocol's status and parameters | | 423 | SoroswapPairError | An error occurred with a Soroswap liquidity pair | Verify the pair exists and has sufficient liquidity | #### Blend Strategy Errors (451–455) | Code | Name | Cause | Solution/Tip | | - | - | - | - | | 451 | AmountBelowMinDust | The amount is below the Blend protocol's minimum dust threshold | Increase the amount above the minimum dust requirement | | 452 | UnderlyingAmountBelowMin | The underlying token amount is below the minimum | Increase the underlying amount | | 453 | BTokensAmountBelowMin | The bToken amount is below the minimum | Increase the deposit to receive more bTokens | | 454 | InternalSwapError | An error occurred during an internal swap within the strategy | Check the swap route and liquidity availability | | 455 | SupplyNotFound | The Blend supply pool was not found | Verify the Blend pool is correctly configured and active | ### Deposit with `invest: true` stays idle #### Symptom You deposit with `invest: true` (the API default), the transaction succeeds, but the funds show up under `idle_amount` in `fetch_total_managed_funds` and `invested_amount` stays at `0`. No error is returned and no `Invest` event is emitted. #### Why Does This Happen? `invest` does not pick a strategy. It tells the vault to split the deposit across its strategies **in the same proportion as the funds already invested**. On a vault that has never invested anything, that proportion is empty, so the contract skips the asset and keeps the deposit idle. It is the first deposit of every new vault, by design. You will hit it when: * The vault was created from the Console with **Deposit on creation** off, or with **Auto-invest deposited funds** off. * The vault was created with `POST /factory/create-vault` or `POST /factory/create-vault-deposit` and the [first rebalance](/integration-guide/creating-a-defindex-vault/index#step-5-first-rebalance) was never run. * Every strategy was unwound to zero (for example after a rescue), so there is no allocation left to follow. #### Fix: One Invest Rebalance The **Manager** or the **Rebalance Manager** ([Vault Roles](/integration-guide/vault-roles)) runs `rebalance` once, with one `Invest` instruction per strategy for the idle amount. Three ways to do it: * **Console**: open the vault, go to the **Admin** tab, add a **Rebalance** instruction of type **Invest** with the strategy and the amount in stroops, and sign with the manager wallet. * **API**: `POST /vault/{vaultAddress}/rebalance` with `{ "caller": "", "instructions": [{ "type": "Invest", "strategy_address": "", "amount": }] }`, then sign and send the XDR. See [Vault Administration](/advanced-documentation/direct-contract-calls/vault-administration#rebalance). * **stellar-cli**: `rebalance --caller --instructions '[{"Invest":["", ""]}]'`, as in [Step 5 of Creating a Vault](/integration-guide/creating-a-defindex-vault/index#step-5-first-rebalance). Once the vault holds an allocation, every later deposit with `invest: true` is invested automatically in that proportion. If you created several vaults at once, each one needs its own first `Invest`. ### Withdrawing All — Dust Left Behind #### Why Does This Happen? When withdrawing all shares, a tiny residual balance (typically 1–3 stroops per asset) may remain. This is by design, not a bug. The vault calculates each asset's withdrawal amount using **integer floor division**: ``` withdrawal_amount = (total_asset × user_shares) / total_shares ``` Since Soroban uses integer arithmetic (no decimals), the division **truncates** any fractional stroop. In multi-asset vaults, this truncation can happen once per asset per division step, compounding to a few stroops total. This behavior is intentional: it prevents the vault from ever paying out more than it holds. #### How Much Dust? Typically **1–3 stroops per asset** (1 stroop = 0.0000001 XLM or the smallest unit of a Soroban token). This is economically negligible. #### Workaround: Two-Step Withdraw If you need to recover the dust, use a two-step approach: ```typescript theme={null} // Step 1: Withdraw all shares const userShares = await defindexSdk.getUserShares(vaultAddress, userAddress); const minAmountsOut = vaultAssets.map(() => 0n); // accept any amount await defindexSdk.withdraw(vaultAddress, { withdrawShares: userShares, minAmountsOut, from: userAddress, }); // Step 2: Check for remaining dust const remainingShares = await defindexSdk.getUserShares(vaultAddress, userAddress); if (remainingShares > 0n) { // Withdraw the remaining dust const dustMinAmounts = vaultAssets.map(() => 0n); await defindexSdk.withdraw(vaultAddress, { withdrawShares: remainingShares, minAmountsOut: dustMinAmounts, from: userAddress, }); } ``` ## Soroban Transaction Errors These are Stellar/Soroban transaction-level errors that occur before or outside of contract execution. They appear in the transaction result rather than in contract event logs. | Error | Cause | Solution | | - | - | - | | `tx_failed` | One or more operations failed | Check operation-level result codes and contract error codes (contract error tables above) | | `tx_bad_seq` | Wrong sequence number | Re-fetch the transaction from the API; Soroban resource estimates are ledger-specific | | `tx_insufficient_fee` | Fee-bump per-op rate too low | Increase base fee ≥ inner tx fee (see [Sponsored Transactions](/integration-guide/guides-and-tutorials/sponsored-transactions#fee-considerations)) | | `tx_too_late` | Timebounds expired before submission | Re-fetch fresh XDR and submit promptly | | `tx_too_early` | Timebounds not yet valid | Wait for the valid time window or re-fetch the transaction | | `tx_bad_auth` | Missing or invalid signature | Ensure all required signers have signed the transaction | | `tx_insufficient_balance` | Source account lacks XLM for fee | Fund the fee-paying account with enough XLM | | `tx_soroban_invalid` | Invalid Soroban transaction structure | Check that contract invocation arguments match the expected types | ## Frequently Asked Questions (FAQ) **Q: My transaction fails with `WrongAmountsLength` (112). What does this mean?** * A: The number of amounts you provided does not match the number of assets in the vault. Double-check your input arrays. **Q: What should I do if I get `InsufficientOutputAmount` (160)?** * A: The vault could not provide the minimum output you requested. Try lowering your minimums or check if the vault has enough liquidity. **Q: How do I know which error code was returned?** * A: Inspect the transaction response object. The error code will be included in the failure reason or logs. **Q: How can I debug contract errors further?** * A: Review the contract's `error.rs` file for detailed error definitions. Use simulation and logging to narrow down the cause. **Q: Are there any environment setup issues I should be aware of?** * A: Yes. Ensure all required environment variables are set, dependencies are installed, and you are using the correct network and contract addresses. **Q: When I withdraw a specific amount, why might I receive slightly more than requested?** * A: Due to the fluctuating ratio between the underlying asset and vault shares (caused by Blend strategy gains) and the Soroban contract's handling of the smallest asset unit ("stroop"), the contract uses ceiling division to calculate the shares to burn. This ensures you receive *at least* the requested amount, but it can sometimes result in a slightly higher output. The contract prioritizes fulfilling the minimum withdrawal amount. **Q: When I deposit a specific amount, will I always receive the same number of shares?** * A: No. Similar to withdrawals, the number of shares you receive when depositing a fixed amount of the underlying asset can vary. This is because the ratio between the asset and shares changes constantly. A deposit made moments apart can yield slightly different share amounts. **Q: I deposited with `invest: true` but the funds are idle. Is the flag ignored?** * A: No. `invest` follows the vault's current allocation, and a vault that has never invested has none, so the first deposit stays idle. The manager runs one `Invest` rebalance and later deposits invest on their own. See [Deposit with `invest: true` stays idle](/integration-guide/troubleshooting#deposit-with-invest-true-stays-idle). **Q: I withdrew all my shares but still have a tiny balance (1–3 stroops). Is this a bug?** * A: No. This is expected behavior due to integer floor division in the contract. See [Withdrawing All — Dust Left Behind](/integration-guide/troubleshooting#withdrawing-all--dust-left-behind) for a full explanation and workaround. ## Additional Resources * [DeFindex Protocol Documentation](https://github.com/paltalabs) * [Smart Contract Error Codes](https://github.com/defindex-io/stellar-contracts/blob/main/vault/src/error.rs) If you encounter an issue not covered here, please open an issue on the project's GitHub repository. # Deposit Source: https://docs.defindex.io/integration-guide/vault-operations/deposit How to deposit funds into a DeFindex vault through the API. To call the contract directly instead, see [Vault Methods](/advanced-documentation/direct-contract-calls/vault-methods). ## Overview Deposits allow you to add assets to a vault, with the option to automatically invest them into the vault's strategies or keep them as idle funds. All deposit operations require specifying amounts, user addresses, and slippage parameters. ## Implementation ```typescript theme={null} const vaultAddress = 'CAQ6PAG4X6L7LJVGOKSQ6RU2LADWK4EQXRJGMUWL7SECS7LXUEQLM5U7'; async function deposit( amount: number, user: string, apiClient: ApiClient, signerFunction: (tx: string) => string ) { // Step 1: Request an unsigned transaction from the API const { xdr: unsignedTx } = await apiClient.postData("deposit", vaultAddress, { amounts: [amount], caller: user }); // Step 2: Sign the transaction (implement your own signer) const signedTx = signerFunction(unsignedTx); // Step 3: Send the signed transaction back to the API const response = await apiClient.send(signedTx); return response; } ``` ## Request Parameters ```javascript theme={null} { amounts: [10000000], // Array of amounts for each vault asset (7 decimals for XLM) caller: userAddress, // User's wallet address invest: true, // Auto-invest into strategies (recommended: true) slippageBps: 50 // 0.5% slippage tolerance (optional, default: 0) } ``` > [!WARNING] > > `invest: true` splits the deposit in the same proportion as the funds the vault already has invested. On a vault that has never invested anything there is nothing to follow, so the deposit stays idle and no error is raised. The Manager or Rebalance Manager runs one `Invest` rebalance and later deposits invest automatically. See [Deposit with `invest: true` stays idle](/integration-guide/troubleshooting#deposit-with-invest-true-stays-idle). ## Return Values A deposit returns: * **Deposited amounts**: The actual amounts deposited for each asset * **Vault shares minted**: Number of vault shares issued to the depositor * **Investment allocations** (if `invest = true`): Details of how funds were allocated across strategies # Get APY Source: https://docs.defindex.io/integration-guide/vault-operations/get-apy Fetches the vault's current APY, net of the fee the vault charges. ```typescript theme={null} const vault = 'CAQ6PAG4X6L7LJVGOKSQ6RU2LADWK4EQXRJGMUWL7SECS7LXUEQLM5U7'; async function apy(apiClient: ApiClient): number { const {apy} = await apiClient.getData("apy", vault); return apy; } ``` # Get Balance Source: https://docs.defindex.io/integration-guide/vault-operations/get-balance Fetches a user's balance in the vault. To call the contract directly instead, see [Vault Methods](/advanced-documentation/direct-contract-calls/vault-methods). ```typescript theme={null} const vault = 'CAQ6PAG4X6L7LJVGOKSQ6RU2LADWK4EQXRJGMUWL7SECS7LXUEQLM5U7'; async function balance(user: string, apiClient: ApiClient): bigint { const {underlyingBalance: balance} = await apiClient.getData("balance", vault, { from: user }); return BigInt(balance[0]); } ``` # Vault Operations Source: https://docs.defindex.io/integration-guide/vault-operations/index Everything a wallet or app does against a live vault, through the API. The API builds each transaction, you sign it and send it back. * [Deposit](/integration-guide/vault-operations/deposit): add assets to a vault * [Withdraw](/integration-guide/vault-operations/withdraw): take them back out * [Get Balance](/integration-guide/vault-operations/get-balance): what a user holds * [Get APY](/integration-guide/vault-operations/get-apy): what the vault is yielding, net of fees * [Rescue](/integration-guide/vault-operations/rescue): pull funds out of a strategy in an emergency **Shares, and dfTokens.** A deposit does not credit a number in a database. The vault mints **dfTokens** to the user's own address, shares that represent their slice of it. Nothing is minted when the vault earns, so the shares stay put and each one becomes worth more, which is where the APY comes from. `balance` returns `underlyingBalance`, the shares already converted to the vault's asset, so most integrations never handle the share count directly. The ones that do, because dfTokens are transferable like any other token, have [a guide](/integration-guide/guides-and-tutorials/deposit-and-transfer-dftokens). The client setup is in the [Quickstart](/integration-guide/quickstart). Vault addresses are on [Contract Deployments](/contract-deployments/index). To call the vault contract yourself rather than going through the API, see [Direct Contract Calls](/advanced-documentation/direct-contract-calls/index). > [card] [Operate your vault from the Console](https://console.defindex.io) > > Every operation on this page is also a click at console.defindex.io: deposit and withdraw with a connected wallet, and rebalance, rescue, or upgrade from the vault's Admin tab. # Rescue Source: https://docs.defindex.io/integration-guide/vault-operations/rescue Emergency withdrawal of a vault's funds out of a strategy and back into the vault, where only users can withdraw them. Rescue is for when an underlying protocol becomes risky. It unwinds the position, returns the capital to the vault as [idle funds](/products/vaults#idle-funds), and pauses the strategy so nothing is invested back into it. User withdrawals stay open throughout: no role can freeze them. Only the Vault Manager or the Emergency Manager can call it. See [Vault Roles](/integration-guide/vault-roles). ## Running it > [card] [Rescue from the Console](https://console.defindex.io) > > The fastest path in an emergency: open your vault at console.defindex.io and trigger the rescue from the Admin tab, signing with the connected Manager or Emergency Manager wallet. Ready-made scripts are in [paltalabs/defindex-rescue](https://github.com/paltalabs/defindex-rescue), which also covers rebalancing idle funds: ```bash theme={null} pnpm rescue ``` The scripts can either sign and submit with a secret key, or build and simulate the transaction and write the unsigned XDR to a file, for a hardware wallet or a multisig to sign. Set `VAULT_ADDRESS` and one of `SIGNER_SECRET` or `SIGNER_PUBLIC_KEY`. To call the contract method yourself, see [Vault Administration](/advanced-documentation/direct-contract-calls/vault-administration). # Withdraw Source: https://docs.defindex.io/integration-guide/vault-operations/withdraw Withdraws funds from a DeFindex vault. To call the contract directly instead, see [Vault Methods](/advanced-documentation/direct-contract-calls/vault-methods). ```typescript theme={null} const vault = 'CAQ6PAG4X6L7LJVGOKSQ6RU2LADWK4EQXRJGMUWL7SECS7LXUEQLM5U7'; async function withdraw(amount: number, user: string, apiClient: ApiClient, signerFunction: (tx: string) => string) { const { xdr: unsignedTx } = await apiClient.postData("withdraw", vault, { amounts: [amount], caller: user }); // This should be done by implementer const signedTx = signerFunction(unsignedTx); const response = await apiClient.send(signedTx); return response; } ``` # Vault Roles Source: https://docs.defindex.io/integration-guide/vault-roles **Roles** are unique identifiers that assign specific responsibilities within the vault and are the only entities with privileges to perform critical actions. Each role is associated with an `Address` that represents the entity responsible for that function. None of these roles can withdraw funds from the users. Since each role is just an `Address`, any role can be assigned to a **smart contract** instead of a regular wallet. This enables policy-based or role-access control patterns — for example, a contract acting as the Manager could define its own internal rules, conditions, or sub-roles to govern who is allowed to trigger actions on behalf of that role. Also, when deploying a vault, the deploying address can be any address — it doesn't need to be tied to the Manager or any other role. In other words, a vault can be set up on behalf of someone else. The roles are: * **Vault Manager** (`Manager`) * Primary owner of the vault * Controls vault settings, role assignments, and contract upgrades * Is included in the authorization check for every role-restricted function — can perform any action that Emergency Manager, Rebalance Manager, or Fee Receiver can perform, without needing to hold those roles * The only role that can manually lock fees (`lock_fees`) or release fees (`release_fees`). Note that fee locking also happens automatically on every deposit and withdraw — `lock_fees` is for triggering it manually * The only role that can upgrade the contract code (only if the vault was deployed as upgradable) * The only role that can change the vault's performance fee (the new rate is supplied as the optional `new_fee_bps` argument when calling `lock_fees`) * Can update any role address, including its own * *Recommendation*: Use a multisig wallet or a policy-based smart contract. * **Rebalance Manager** (`RebalanceManager`) * Executes rebalancing instructions that move funds across strategies * *Recommendation*: Use a multisig wallet or a policy-based smart contract. * **Fee Receiver** (`VaultFeeReceiver`) * Receives fees collected by the vault * Triggers distribution of already-locked fees to vault and protocol receivers by calling `distribute_fees` * Can also update the fee receiver address (shared with Manager) * Cannot lock or release fees, nor change the performance fee — those are Manager-only * *Recommendation*: Use a dedicated wallet, and make sure it has trustlines set up for the vault's underlying assets so fee distributions don't fail * **Emergency Manager** (`EmergencyManager`) * Can unwind all funds from a specific Strategy and store them as idle funds in the Vault,\ automatically pausing that Strategy (`rescue`). * Can pause a specific strategy, blocking deposits to it * Can unpause a specific strategy * Cannot access the vault balance or withdraw user funds directly * *Recommendation*: Implement as an automated bot or delegate it ## Role Permissions | Action | Manager | Emergency Manager | Rebalance Manager | Fee Receiver | | - | :-: | :-: | :-: | :-: | | Rescue assets from strategy | ✅ | ✅ | — | — | | Pause strategy | ✅ | ✅ | — | — | | Unpause strategy | ✅ | ✅ | — | — | | Rebalance across strategies | ✅ | — | ✅ | — | | Receive fees | — | — | — | ✅ | | Distribute fees | ✅ | — | — | ✅ | | Manually lock / release fees (`lock_fees` / `release_fees`) | ✅ | — | — | — | | Change performance fee (via `lock_fees`) | ✅ | — | — | — | | Upgrade contract code (if the vault is upgradable) | ✅ | — | — | — | | Change Manager | ✅ | — | — | — | | Change Emergency Manager | ✅ | — | — | — | | Change Rebalance Manager | ✅ | — | — | — | | Change Fee Receiver | ✅ | — | — | ✅ | ## Protocol Fee Receiver In addition to the vault roles above, each vault also stores a **DeFindex Protocol Fee Receiver** (`DeFindexProtocolFeeReceiver`). This is not a vault role: it cannot call any function on the vault. It is a passive recipient address set at vault initialization that automatically receives a share of the locked fees whenever `distribute_fees` is called. That share is the `DeFindexProtocolFeeRate` (in basis points of the locked fee), also set at initialization and fixed thereafter. The factory passes its own current default rate (`defindex_fee`) into every vault it creates, and the factory admin can change that default for future vaults with `set_defindex_fee`. A vault keeps the rate it was created with, so vaults created at different times can carry different rates. Read a vault's rate with `get_fees`, or from `feesBps.defindexFee` in `GET /vault/{address}`. ## Role Assignment and Updates Roles are set at deployment and can be updated afterward by calling the corresponding setter function. Only the Manager can change most roles — the Fee Receiver address is the only one that either the Manager or the current Fee Receiver can update. | Role | Who can change it | | - | - | | Manager | Manager | | Emergency Manager | Manager | | Rebalance Manager | Manager | | Fee Receiver | Manager or Fee Receiver | > [card] [Assign roles in the Console](https://console.defindex.io) > > Roles are set when you create the vault at console.defindex.io, and the vault's Roles tab is where you rotate them later. # Fees and revenue Source: https://docs.defindex.io/intro/fees In DeFindex, fees are performance fees: you set the rate, they are charged on the yield your vault generates, and they are split between you and DeFindex. ## How the fee works Your end users deposit into a vault, and the vault generates yield across its diversified strategies. Fees are charged on top of that yield, and are split between you (the neobank, fintech or wallet) and the DeFindex protocol. It is a performance fee, charged continuously, on every transaction that touches the vault, so your users are charged on the gains. You set the rate, and you can change it whenever you want. Our API gives you the APY already net of all of it, so the number you show your users is the number they get. > [!NOTE] > > If you need to charge deposit or management fees, [talk to our team](https://paltalabs.io/esteban/cal). ## A worked example A vault charging 20%: ![How a vault fee is split](https://mintcdn.com/defindex/ug30IPjHJU5kK9-E/images/fees.png?fit=max\&auto=format\&n=ug30IPjHJU5kK9-E\&q=85\&s=b82488b568008d5b6e9619d7c83c0bd0) Your user deposits 1,000 and the vault earns 100 on top of it. The fee comes out of that 100, and at 20% that is 20. Your user's balance ends at 1,080, and the 20 is split between you and DeFindex. With a 50% DeFindex share, as in the picture, that is 10 each. ## How DeFindex is paid DeFindex keeps a share of the fee you set, and you keep the rest. That share is a percentage of your fee, not an extra charge, and it is fixed in each vault when the vault is created: the vault copies the protocol's default share at that moment and keeps it. So it is not the same for every vault. A vault created while the default was 50% splits the fee 50/50. You can read your vault's share from our API at any time. There is no other charge to you or to your users. If you set the fee to 0%, nobody is paid. ## When it reaches you Fees accumulate in the vault and you can claim them at any time. You can automate that through our API or from the Console. At a minimum they are collected once a month. ## Stable APY A vault's APY fluctuates. With the Stable APY product you offer a fixed rate instead, and everything the vault earns above it is charged as fee. Say the yield moves between 6% and 10% and you offer 4%. Whatever the vault earns above that 4% becomes your fee. See the [Stable APY product](/products/stable-apy). > [card] [Talk to the team](https://paltalabs.io/esteban/cal) > > Book a call and we go through your numbers. # What is DeFindex Source: https://docs.defindex.io/intro/what-is-defindex DeFindex is yield infrastructure. You integrate it once and your users get a balance that earns, without you building or auditing any DeFi yourself. First, lets define some concepts: **Yield** is what money earns while it sits somewhere that pays for it. DeFindex does not create yield. It comes from outside: a lending market, an exchange, a tokenized bond. **A strategy** is code that knows how to earn in one of those places and how to get the money back out. We write each one and have it audited before it ships. **A vault** is the contract your users deposit into. It holds the money, spreads it across the strategies you picked, and reports back one balance and one APY, which is that yield written as a yearly rate. ## Five layers, and only one holds the money | Layer | What it is | Who controls it | | - | - | - | | **You** | The neobank, fintech or wallet your users see. You own a vault and set its fee | You | | **The API** | What you integrate against. It builds the transactions your app signs and sends, and reads balances and APY back | DeFindex | | **The vault** | The contract holding your users' deposits and spreading them across the strategies you picked. Usually one per partner | You | | **A strategy** | Code that connects to one yield source and knows how to earn there | DeFindex, audited before it ships | | **The yield source** | The outside protocol the return actually comes from: a lending market, an exchange, a tokenized bond | Its own team, not DeFindex | Only the vault holds money. The two layers above it move instructions, and the two below are where the vault sends money to earn and takes it back. The bottom layer is the one DeFindex does not own, so its risk is its own. The [audits of those protocols](/advanced-documentation/risks-and-audits) are listed alongside ours. From your side it is a few API calls. Your app shows one number, your users put money in and take it out whenever they want, and you charge a fee on what the vault earns. # Why DeFindex Source: https://docs.defindex.io/intro/why-defindex The case for not building this yourself. You want a savings feature in your app. The choice is between integrating a yield protocol yourself and integrating DeFindex, which sits on top of those protocols. ## What you get * **One integration, in one day.** The API builds the transactions and your user signs them. No smart contract code on your side. * **A margin you control.** You set a fee on the yield, and the spread between what the strategies earn and what you show is yours. See [Fees and revenue](/intro/fees). * **A fixed rate if you want one.** [Stable APY](/products/stable-apy) manages the fee inside bounds you set so the APY your users see tracks a target. * **A way out for everyone at once.** If a protocol underneath turns risky, one call pulls every user's funds back to the vault. Read on. ## Against integrating directly A lending market or an AMM is a protocol, not a product. It lends and it pays a rate. Everything a savings feature needs around that, you build. | | Direct to protocol | DeFindex | | - | :-: | :-: | | Your fee on the yield | No | Yes, up to 90% | | Per user balances and APY | You build and maintain them | From the API | | Several yield sources behind one balance | You build the allocation | Yes | | Emissions reinvested for depositors | You claim and reinvest yourself | Yes, autocompounded | | Collective emergency exit | No | Yes, one call | | A fixed rate you can advertise | No | [Stable APY](/products/stable-apy) | | Transactions built for you | No | API and Console | The fee row is the one partners are surprised by. A protocol pays its rate to whoever holds the position, and it has no notion of an integrator taking a cut. To earn on the yield you have to sit between your users and the protocol, keep the accounting, and charge on the gain. That is a vault, and building one is the work DeFindex already did and got audited. The row that matters most is the emergency exit. If the protocol underneath gets risky and each of your users holds their own position, there is nothing you can do for them. You can warn each one and hope each one signs a withdrawal, and most do not. In DeFindex it is one call, `rescue`, and it stays non custodial: the role pulls the funds out of the risky place and into the vault, where only the users can withdraw them. ## When not to use DeFindex If you only want to point each user at a single protocol, hold nothing in between, and earn nothing on it, you do not need a vault and you do not need us. > [card] [Talk to the team](https://paltalabs.io/esteban/cal) > > Book a call and we work out what you need. # Media Kit Source: https://docs.defindex.io/media-kit/index Everything you need to put our logo in your announcement. ## Brand Identity **Name:** DeFindex (always written with capital "D" and "F") **Domain:** defindex.io *** ## DeFindex Symbol Two intertwined arrows forming a cyclical pattern, representing automated reinvest. Download links under each image. All files have a transparent background; PNGs are high resolution. The Monochrome White preview is shown on Dark Green so it's visible; the file itself is transparent. | Light Background | Dark Background | Monochrome Dark Green | Monochrome White | | - | - | - | - | | ![Symbol Gradient](https://mintcdn.com/defindex/ug30IPjHJU5kK9-E/images/symbol-gradient.svg?fit=max\&auto=format\&n=ug30IPjHJU5kK9-E\&q=85\&s=b6e33345724039538ef7855c032b563a) | ![Symbol White](https://mintcdn.com/defindex/ug30IPjHJU5kK9-E/images/symbol-white.svg?fit=max\&auto=format\&n=ug30IPjHJU5kK9-E\&q=85\&s=75ad657c164a578dff535750431d2609) | ![Symbol Black](https://mintcdn.com/defindex/ug30IPjHJU5kK9-E/images/symbol-black.svg?fit=max\&auto=format\&n=ug30IPjHJU5kK9-E\&q=85\&s=c16c3cd07ea4c7d9d169c3fae427737a) | ![Symbol Mono White](https://mintcdn.com/defindex/wvr4tvM5eq7BYTv3/images/brand/backgrounds/symbol-04.svg?fit=max\&auto=format\&n=wvr4tvM5eq7BYTv3\&q=85\&s=b91474443dc77be2d1fc541ae25b37f3) | | [SVG](/images/brand/symbol-gradient.svg) · [PNG](/images/brand/symbol-gradient.png) | [SVG](/images/brand/symbol-white.svg) · [PNG](/images/brand/symbol-white.png) | [SVG](/images/brand/symbol-black.svg) · [PNG](/images/brand/symbol-black.png) | [SVG](/images/brand/symbol-mono-white.svg) · [PNG](/images/brand/symbol-mono-white.png) | *** ## DeFindex Logo Complete signature: Symbol + Wordmark in Familjen Grotesk Bold. ### Horizontal | Light Background | Dark Background | Monochrome Dark Green | Monochrome White | | - | - | - | - | | ![Logo Horizontal Gradient](https://mintcdn.com/defindex/ug30IPjHJU5kK9-E/images/logo-horizontal-gradient.svg?fit=max\&auto=format\&n=ug30IPjHJU5kK9-E\&q=85\&s=10034e0b24f9da2afec8f2e94da6d029) | ![Logo Horizontal White](https://mintcdn.com/defindex/ug30IPjHJU5kK9-E/images/logo-horizontal-white.svg?fit=max\&auto=format\&n=ug30IPjHJU5kK9-E\&q=85\&s=3f7bd3a147badb6c45c3d8d80a535f68) | ![Logo Horizontal Black](https://mintcdn.com/defindex/ug30IPjHJU5kK9-E/images/logo-horizontal-black.svg?fit=max\&auto=format\&n=ug30IPjHJU5kK9-E\&q=85\&s=8c4d72096fb0056f6cbd9defd362d278) | ![Logo Horizontal Mono White](https://mintcdn.com/defindex/wvr4tvM5eq7BYTv3/images/brand/backgrounds/logo-horizontal-04.svg?fit=max\&auto=format\&n=wvr4tvM5eq7BYTv3\&q=85\&s=15ef0c9ece7c8001f7fbd45c63ebf828) | | [SVG](/images/brand/logo-horizontal-gradient.svg) · [PNG](/images/brand/logo-horizontal-gradient.png) | [SVG](/images/brand/logo-horizontal-white.svg) · [PNG](/images/brand/logo-horizontal-white.png) | [SVG](/images/brand/logo-horizontal-black.svg) · [PNG](/images/brand/logo-horizontal-black.png) | [SVG](/images/brand/logo-horizontal-mono-white.svg) · [PNG](/images/brand/logo-horizontal-mono-white.png) | ### Vertical | Light Background | Dark Background | Monochrome Dark Green | Monochrome White | | - | - | - | - | | ![Logo Vertical Gradient](https://mintcdn.com/defindex/ug30IPjHJU5kK9-E/images/logo-vertical-gradient.svg?fit=max\&auto=format\&n=ug30IPjHJU5kK9-E\&q=85\&s=edbcae2aed671e6ed547f5257a09cfef) | ![Logo Vertical White](https://mintcdn.com/defindex/ug30IPjHJU5kK9-E/images/logo-vertical-white.svg?fit=max\&auto=format\&n=ug30IPjHJU5kK9-E\&q=85\&s=c6ef397bf9b031de7cde32aa9564f35f) | ![Logo Vertical Black](https://mintcdn.com/defindex/ug30IPjHJU5kK9-E/images/logo-vertical-black.svg?fit=max\&auto=format\&n=ug30IPjHJU5kK9-E\&q=85\&s=e2df0a22759f00285169ac584609971f) | ![Logo Vertical Mono White](https://mintcdn.com/defindex/wvr4tvM5eq7BYTv3/images/brand/backgrounds/logo-vertical-04.svg?fit=max\&auto=format\&n=wvr4tvM5eq7BYTv3\&q=85\&s=dcbd5b252d381c2438f46dcc4bb21af0) | | [SVG](/images/brand/logo-vertical-gradient.svg) · [PNG](/images/brand/logo-vertical-gradient.png) | [SVG](/images/brand/logo-vertical-white.svg) · [PNG](/images/brand/logo-vertical-white.png) | [SVG](/images/brand/logo-vertical-black.svg) · [PNG](/images/brand/logo-vertical-black.png) | [SVG](/images/brand/logo-vertical-mono-white.svg) · [PNG](/images/brand/logo-vertical-mono-white.png) | ### Logo Color Variants | Context | Symbol | Wordmark | | - | - | - | | Light background (primary) | Lavender `#DEC9F4` | Dark Green `#014751` | | Dark background (primary) | Lavender `#DEC9F4` | White `#FFFFFF` | | Monochrome light | Dark Green | Dark Green | | Monochrome dark | White | White | *** ## On Brand Backgrounds Ready-to-use versions with the background included, for avatars, banners and slides. ### Symbol | | | | | | - | - | - | - | | ![Symbol 01](https://mintcdn.com/defindex/wvr4tvM5eq7BYTv3/images/brand/backgrounds/symbol-01.svg?fit=max\&auto=format\&n=wvr4tvM5eq7BYTv3\&q=85\&s=898a503e5a990e65880ce2ab6ef21f83) | ![Symbol 02](https://mintcdn.com/defindex/wvr4tvM5eq7BYTv3/images/brand/backgrounds/symbol-02.svg?fit=max\&auto=format\&n=wvr4tvM5eq7BYTv3\&q=85\&s=ec4178428844d836b38d94fa928942e1) | ![Symbol 03](https://mintcdn.com/defindex/wvr4tvM5eq7BYTv3/images/brand/backgrounds/symbol-03.svg?fit=max\&auto=format\&n=wvr4tvM5eq7BYTv3\&q=85\&s=22e7d9d86f83fdc47523f9c402944258) | ![Symbol 04](https://mintcdn.com/defindex/wvr4tvM5eq7BYTv3/images/brand/backgrounds/symbol-04.svg?fit=max\&auto=format\&n=wvr4tvM5eq7BYTv3\&q=85\&s=b91474443dc77be2d1fc541ae25b37f3) | | White · [SVG](/images/brand/backgrounds/symbol-01.svg) · [PNG](/images/brand/backgrounds/symbol-01.png) | Dark Green · [SVG](/images/brand/backgrounds/symbol-02.svg) · [PNG](/images/brand/backgrounds/symbol-02.png) | White · [SVG](/images/brand/backgrounds/symbol-03.svg) · [PNG](/images/brand/backgrounds/symbol-03.png) | Dark Green · [SVG](/images/brand/backgrounds/symbol-04.svg) · [PNG](/images/brand/backgrounds/symbol-04.png) | | ![Symbol 05](https://mintcdn.com/defindex/wvr4tvM5eq7BYTv3/images/brand/backgrounds/symbol-05.svg?fit=max\&auto=format\&n=wvr4tvM5eq7BYTv3\&q=85\&s=ecaa17afcb1ab0e70de79f3eeb3156bd) | ![Symbol 06](https://mintcdn.com/defindex/wvr4tvM5eq7BYTv3/images/brand/backgrounds/symbol-06.svg?fit=max\&auto=format\&n=wvr4tvM5eq7BYTv3\&q=85\&s=58900fe7100ef5c259cd032014da38f7) | ![Symbol 07](https://mintcdn.com/defindex/wvr4tvM5eq7BYTv3/images/brand/backgrounds/symbol-07.svg?fit=max\&auto=format\&n=wvr4tvM5eq7BYTv3\&q=85\&s=9f75b8f3847315fc593d1bab5319aaae) | ![Symbol 08](https://mintcdn.com/defindex/wvr4tvM5eq7BYTv3/images/brand/backgrounds/symbol-08.svg?fit=max\&auto=format\&n=wvr4tvM5eq7BYTv3\&q=85\&s=a0fdb984eaff3b3c915ab79c48cffc49) | | Lavender · [SVG](/images/brand/backgrounds/symbol-05.svg) · [PNG](/images/brand/backgrounds/symbol-05.png) | Light Cyan · [SVG](/images/brand/backgrounds/symbol-06.svg) · [PNG](/images/brand/backgrounds/symbol-06.png) | Light Green · [SVG](/images/brand/backgrounds/symbol-07.svg) · [PNG](/images/brand/backgrounds/symbol-07.png) | Coral · [SVG](/images/brand/backgrounds/symbol-08.svg) · [PNG](/images/brand/backgrounds/symbol-08.png) | ### Horizontal | | | | | | - | - | - | - | | ![Horizontal 01](https://mintcdn.com/defindex/wvr4tvM5eq7BYTv3/images/brand/backgrounds/logo-horizontal-01.svg?fit=max\&auto=format\&n=wvr4tvM5eq7BYTv3\&q=85\&s=dcb6ae0a9367dcb5e1542a2425633541) | ![Horizontal 02](https://mintcdn.com/defindex/wvr4tvM5eq7BYTv3/images/brand/backgrounds/logo-horizontal-02.svg?fit=max\&auto=format\&n=wvr4tvM5eq7BYTv3\&q=85\&s=ed9909ae1b721925887d03777710acf5) | ![Horizontal 03](https://mintcdn.com/defindex/wvr4tvM5eq7BYTv3/images/brand/backgrounds/logo-horizontal-03.svg?fit=max\&auto=format\&n=wvr4tvM5eq7BYTv3\&q=85\&s=562bcaf9313998dcc0288f181b09dcad) | ![Horizontal 04](https://mintcdn.com/defindex/wvr4tvM5eq7BYTv3/images/brand/backgrounds/logo-horizontal-04.svg?fit=max\&auto=format\&n=wvr4tvM5eq7BYTv3\&q=85\&s=15ef0c9ece7c8001f7fbd45c63ebf828) | | White · [SVG](/images/brand/backgrounds/logo-horizontal-01.svg) · [PNG](/images/brand/backgrounds/logo-horizontal-01.png) | Dark Green · [SVG](/images/brand/backgrounds/logo-horizontal-02.svg) · [PNG](/images/brand/backgrounds/logo-horizontal-02.png) | White · [SVG](/images/brand/backgrounds/logo-horizontal-03.svg) · [PNG](/images/brand/backgrounds/logo-horizontal-03.png) | Dark Green · [SVG](/images/brand/backgrounds/logo-horizontal-04.svg) · [PNG](/images/brand/backgrounds/logo-horizontal-04.png) | | ![Horizontal 05](https://mintcdn.com/defindex/wvr4tvM5eq7BYTv3/images/brand/backgrounds/logo-horizontal-05.svg?fit=max\&auto=format\&n=wvr4tvM5eq7BYTv3\&q=85\&s=c82c14007eb45d1fdc6c5a459b55ca31) | ![Horizontal 06](https://mintcdn.com/defindex/wvr4tvM5eq7BYTv3/images/brand/backgrounds/logo-horizontal-06.svg?fit=max\&auto=format\&n=wvr4tvM5eq7BYTv3\&q=85\&s=ac0b5c4e67931e68a9941fdd638f4794) | ![Horizontal 07](https://mintcdn.com/defindex/wvr4tvM5eq7BYTv3/images/brand/backgrounds/logo-horizontal-07.svg?fit=max\&auto=format\&n=wvr4tvM5eq7BYTv3\&q=85\&s=9de607961134e9da3be0e51f55066439) | ![Horizontal 08](https://mintcdn.com/defindex/wvr4tvM5eq7BYTv3/images/brand/backgrounds/logo-horizontal-08.svg?fit=max\&auto=format\&n=wvr4tvM5eq7BYTv3\&q=85\&s=3ab9f157075d0507a9fdc81a3ae232bc) | | Lavender · [SVG](/images/brand/backgrounds/logo-horizontal-05.svg) · [PNG](/images/brand/backgrounds/logo-horizontal-05.png) | Light Cyan · [SVG](/images/brand/backgrounds/logo-horizontal-06.svg) · [PNG](/images/brand/backgrounds/logo-horizontal-06.png) | Light Green · [SVG](/images/brand/backgrounds/logo-horizontal-07.svg) · [PNG](/images/brand/backgrounds/logo-horizontal-07.png) | Coral · [SVG](/images/brand/backgrounds/logo-horizontal-08.svg) · [PNG](/images/brand/backgrounds/logo-horizontal-08.png) | ### Vertical | | | | | | - | - | - | - | | ![Vertical 01](https://mintcdn.com/defindex/wvr4tvM5eq7BYTv3/images/brand/backgrounds/logo-vertical-01.svg?fit=max\&auto=format\&n=wvr4tvM5eq7BYTv3\&q=85\&s=40546d34d73e5b4bdf41cb13172bb435) | ![Vertical 02](https://mintcdn.com/defindex/wvr4tvM5eq7BYTv3/images/brand/backgrounds/logo-vertical-02.svg?fit=max\&auto=format\&n=wvr4tvM5eq7BYTv3\&q=85\&s=931710665bbb5c2fdab8b7032712c65d) | ![Vertical 03](https://mintcdn.com/defindex/wvr4tvM5eq7BYTv3/images/brand/backgrounds/logo-vertical-03.svg?fit=max\&auto=format\&n=wvr4tvM5eq7BYTv3\&q=85\&s=d5e1cfe6e5d028e76c52c03ab1738435) | ![Vertical 04](https://mintcdn.com/defindex/wvr4tvM5eq7BYTv3/images/brand/backgrounds/logo-vertical-04.svg?fit=max\&auto=format\&n=wvr4tvM5eq7BYTv3\&q=85\&s=dcbd5b252d381c2438f46dcc4bb21af0) | | White · [SVG](/images/brand/backgrounds/logo-vertical-01.svg) · [PNG](/images/brand/backgrounds/logo-vertical-01.png) | Dark Green · [SVG](/images/brand/backgrounds/logo-vertical-02.svg) · [PNG](/images/brand/backgrounds/logo-vertical-02.png) | White · [SVG](/images/brand/backgrounds/logo-vertical-03.svg) · [PNG](/images/brand/backgrounds/logo-vertical-03.png) | Dark Green · [SVG](/images/brand/backgrounds/logo-vertical-04.svg) · [PNG](/images/brand/backgrounds/logo-vertical-04.png) | | ![Vertical 05](https://mintcdn.com/defindex/wvr4tvM5eq7BYTv3/images/brand/backgrounds/logo-vertical-05.svg?fit=max\&auto=format\&n=wvr4tvM5eq7BYTv3\&q=85\&s=ba4f187760e4d3cf9ad1b160c85ec01e) | ![Vertical 06](https://mintcdn.com/defindex/wvr4tvM5eq7BYTv3/images/brand/backgrounds/logo-vertical-06.svg?fit=max\&auto=format\&n=wvr4tvM5eq7BYTv3\&q=85\&s=f8346ae5bea8d80fee03b530ba9c12cc) | ![Vertical 07](https://mintcdn.com/defindex/wvr4tvM5eq7BYTv3/images/brand/backgrounds/logo-vertical-07.svg?fit=max\&auto=format\&n=wvr4tvM5eq7BYTv3\&q=85\&s=bd5171e786f4f8d527e0bd8d6bff82b3) | ![Vertical 08](https://mintcdn.com/defindex/wvr4tvM5eq7BYTv3/images/brand/backgrounds/logo-vertical-08.svg?fit=max\&auto=format\&n=wvr4tvM5eq7BYTv3\&q=85\&s=288461201ac1f896ce11fa9b046315dc) | | Lavender · [SVG](/images/brand/backgrounds/logo-vertical-05.svg) · [PNG](/images/brand/backgrounds/logo-vertical-05.png) | Light Cyan · [SVG](/images/brand/backgrounds/logo-vertical-06.svg) · [PNG](/images/brand/backgrounds/logo-vertical-06.png) | Light Green · [SVG](/images/brand/backgrounds/logo-vertical-07.svg) · [PNG](/images/brand/backgrounds/logo-vertical-07.png) | Coral · [SVG](/images/brand/backgrounds/logo-vertical-08.svg) · [PNG](/images/brand/backgrounds/logo-vertical-08.png) | *** ## Color Palette | Color | HEX | RGB | Usage | | - | - | - | - | | **White** | `#FFFFFF` | 255, 255, 255 | Light backgrounds, text on dark | | **Dark Green** | `#014751` | 1, 71, 81 | Primary. Titles, text, backgrounds | | **Lavender** | `#DEC9F4` | 221, 201, 244 | Primary. Logo symbol, accents | | **Light Green** | `#D3FFB4` | 211, 255, 180 | Accent. Highlights, soft backgrounds | | **Light Cyan** | `#D3FBFF` | 211, 251, 255 | Accent. Backgrounds, graphic elements | | **Coral** | `#FC5B31` | 252, 91, 49 | Strong accent. Emphasis, CTAs | ### Color Usage Rules * **White, Dark Green, and Lavender** are frequently used: titles, subtitles, descriptive text * **Light Green, Light Cyan, and Coral** are accent colors: highlights, boxes, buttons * **Coral** is used for emphasis and keywords in italics within headlines * Always ensure contrast and legibility * **Never** use colors outside this palette *** ## Typography | Font | Usage | Weights | | - | - | - | | **Familjen Grotesk** | Headlines, titles, featured info | Regular, Medium, SemiBold, Bold | | **Inter Tight** | Subtitles, body text | Regular, Medium, SemiBold | Both fonts are available on [Google Fonts](https://fonts.google.com/). ### Typography Rules * Headlines: **Familjen Grotesk** Bold or SemiBold * Body text: **Inter Tight** Regular or Medium * Emphasis keyword in headlines: **italic** + **Coral** color * Maintain clear hierarchy * Never mix more than 2 font weights in the same piece * Fallback: `system-ui, -apple-system, "Segoe UI", sans-serif` *** ## Visual Elements ### Glass Elements (3D) Translucent 3D shapes with glassmorphism aesthetic, colored in **duotone** using brand palette combinations. | | | | | - | - | - | | ![Glass 01](https://mintcdn.com/defindex/ug30IPjHJU5kK9-E/images/glass-01.jpg?fit=max\&auto=format\&n=ug30IPjHJU5kK9-E\&q=85\&s=979db96fbad79a762cea7b2341bfbf58) | ![Glass 03](https://mintcdn.com/defindex/ug30IPjHJU5kK9-E/images/glass-03.jpg?fit=max\&auto=format\&n=ug30IPjHJU5kK9-E\&q=85\&s=93852cbc7dabb0d0f7cbadd9138b0446) | ![Glass 05](https://mintcdn.com/defindex/ug30IPjHJU5kK9-E/images/glass-05.jpg?fit=max\&auto=format\&n=ug30IPjHJU5kK9-E\&q=85\&s=5a37fd595f11df88cd638a8ec9ab91b7) | **Rules:** * Always translucent, never solid or opaque * Types: interlocking tori/rings, crystalline shapes, fluid blobs * Use combinations like Dark Green + Lavender, Coral + Light Cyan ### Gradients Soft, diffused gradients using brand palette colors. | | | | - | - | | ![Gradient 01](https://mintcdn.com/defindex/ug30IPjHJU5kK9-E/images/gradient-01.jpg?fit=max\&auto=format\&n=ug30IPjHJU5kK9-E\&q=85\&s=d6c0bf2c09ce3f11b3c53d8c34495ca0) | ![Gradient 03](https://mintcdn.com/defindex/ug30IPjHJU5kK9-E/images/gradient-03.jpg?fit=max\&auto=format\&n=ug30IPjHJU5kK9-E\&q=85\&s=fffa1beefadfc4bc2f713807607da99f) | **Approved combinations:** * Cyan → Light Green → Lavender * Coral → Light Cyan * Lavender → Coral * Light Cyan → Lavender * Light Green → Lavender → Coral Gradients must be **soft and diffused**, never with abrupt transitions. # Boost Source: https://docs.defindex.io/products/boost You fund it, and every cent of it reaches your depositors. Fee control can trim yield that sits above a target. It cannot create yield that is not there. A boost campaign can, because you fund it. ## How a campaign runs You fund a budget that is held for your vault, in the vault's own asset. While the vault sits below its target and the budget still has money in it, funds move from there into the vault, which raises what every depositor holds. Spending stops when the budget does, and the vault returns to its organic rate. Campaigns are per vault and supported for single asset vaults. We register the campaign for you, and once it is active anyone can add funds to it. ## What a boost costs **A boost carries no vault fee.** It arrives as a plain transfer rather than as strategy gains, so nothing is locked on it. Every unit you put in reaches your depositors, and neither you nor DeFindex is paid on it. That makes the fee floor underneath a real decision rather than a formality: * **A floor of zero** hands your users all of the organic yield before the campaign spends anything, and nobody is paid while the vault sits below target. * **A floor above zero** keeps your fee running through the shortfall, which means the campaign has more ground to cover. > [!NOTE] > > [Talk to our team](https://paltalabs.io/esteban/cal) before planning a campaign you expect to earn from, or before setting a floor above zero. The arithmetic turns on your target, your strategy mix and the size of the budget, and it is worth an hour with your numbers. ## Without Stable APY A campaign does not need Stable APY. A vault on an ordinary fixed fee can run one against a target we keep on our side, which is the right shape when you want to lift a rate for a season without handing over control of your fee. ## Custody Boosts only move money in. Nothing here can take a depositor's funds out of the vault or delay a withdrawal. Your budget is held separately per vault, and whatever is left of it can be sent back to an address you name. See [Risks and Audits](/advanced-documentation/risks-and-audits#custody). ## Audit Audited by [Runtime Verification](https://runtimeverification.com/audits) in July 2026, together with the fee proxy. See [Risks and Audits](/advanced-documentation/risks-and-audits). > [card] [The endpoints](/integration-guide/stable-apy) > > Fund a campaign and read its status. # Products Source: https://docs.defindex.io/products/index DeFindex's core product is the Vault, the one a neobank offers its users so they can earn yield. It sources that yield from diversified strategies, and its APY fluctuates. On top of it, DeFindex offers two other tools you can use depending on your needs: a Stable APY or a Boosted APY. And to bring money in and out of your app, Ramps. > [card] [Vaults](/products/vaults) > > Takes deposits, allocates them across strategies, reports one balance and one APY back. > [card] [Stable APY](/products/stable-apy) > > You publish a rate and it holds. What the strategies earn above it becomes fee revenue. > [card] [Boost](/products/boost) > > A budget you fund that tops up what your depositors receive while the vault sits under target. > [card] [Ramps](/products/ramps) > > Pesos in and out of your app, with one integration and one published price. > [card] [Talk to the team](https://paltalabs.io/esteban/cal) > > Book a call and we work out what you need. # Ramps Source: https://docs.defindex.io/products/ramps Pesos in and out of your app, straight into yield, with one integration and one published price. DeFindex Ramps lets your users fund their balance with a bank transfer in Mexican pesos and cash out the same way. The money arrives as USDC, or as CETES (tokenized Mexican treasury bills) that can go straight into a [vault](/products/vaults) and start earning. ## From a bank transfer to a vault ```mermaid theme={null} flowchart LR A["SPEI transfer
in pesos"] -->|free| B["CETES
in your user's wallet"] B -->|deposit| C["Your DeFindex vault
earning"] ``` The ramp is not a separate vendor to onboard. It comes with the same account as your vaults, so the money your users bring in lands where it earns. Cashing out is the same path, backwards. ## Where it works Live in Mexico, with pesos in and out by SPEI (CLABE). Brazil, Argentina and Colombia are available on request: [talk to us](https://paltalabs.io/esteban/cal). Tokens settle on **Stellar, Base, Polygon, Solana, Avalanche or Monad**, so the ramp works with the wallets you already use. ## What it costs One price per route, paid by the user. There is nothing else on top. | Route | Fee | | - | - | | Pesos to CETES | **Free** | | CETES to pesos | 0.15% | | Pesos to USDC, or USDC to pesos | 0.50% | | CETES to USDC, or USDC to CETES | 0.50% | | USDC to USTRY (tokenized US Treasuries) | **Free** | | USTRY to USDC | 0.15% | Entering a treasury bill is free and leaving one costs 0.15%. Changing currency costs 0.50%, applied on top of a published reference rate (Bloomberg for the peso). The fee is calculated on the amount the user sends. You can add your own fee on top. It is folded into the same quote, so your user sees one number, and your part is paid out to you monthly. > [!NOTE] > > Moving a large monthly volume? [Talk to our team](https://paltalabs.io/esteban/cal) about volume pricing. ## A quote, step by step **1. Your user asks for a quote** They pick an amount and a route. The quote already includes every fee, yours too, so the number they see is the number they get. **2. They pay by bank transfer** For pesos in, they send a SPEI transfer to the account in the quote. **3. Tokens land in their wallet** USDC or CETES go to the wallet your user controls, on the network you chose. From there, a deposit puts them in a vault. **4. Every order has a status** Your backend follows each order until it completes. > [card] Example > > Your user pays **MX\$1,000.00** and receives about **53.78 USDC**: the peso at a reference rate of 18.50, minus the 0.50% fee. Rates move, so the real figure is the one in the quote. ## How you get started 1. **We open your ramp account** with the pricing above. 2. **Your company completes KYB** in a hosted flow. You do it once. 3. **Your users complete KYC** in a hosted flow you launch from your app. You do not store their documents. 4. **You integrate the ramp**: request a quote, show it, create the order. We give you the API access and walk your team through it. ## What teams ask first > [accordion] Why not go straight to a ramp provider? > > You can, and you would get a ramp. With DeFindex the pesos land in a vault in the same flow, with one integration and one published price for both. > [accordion] What happens to the money after it lands? > > It stays in your user's wallet as USDC or CETES, or goes straight into your vault. Your user can withdraw and cash out whenever they want. See the [RWA wrapper strategy](/strategies/rwa-wrapper) for how CETES earn inside a vault. > [accordion] Who moves the money? > > Pesos are received and paid out by [Etherfuse](https://www.etherfuse.com), DeFindex's ramp partner in Mexico. Etherfuse operates under a resolution from the CNBV, Mexico's financial regulator, and the assets behind CETES and USTRY are held at regulated Mexican financial institutions. It runs the KYB and KYC checks and issues CETES and USTRY. DeFindex never holds your users' pesos or tokens: the bank transfer goes to Etherfuse, and the tokens go to the wallet your user controls. > [card] [Talk to the team](https://paltalabs.io/esteban/cal) > > We open your ramp account and walk your team through the integration. # Stable APY Source: https://docs.defindex.io/products/stable-apy Publish a rate, and keep what the strategies earn above it. Yield in DeFi floats, and a number that moves every day is a hard thing to put in a savings screen. Stable APY lets you publish one instead: you set a target, and DeFindex adjusts the vault fee so the rate your depositors receive tracks it. The part worth noticing is the upside. Your depositors get the number you advertised, and what the strategies earn above it becomes fee revenue, up to the ceiling you set. Opt in, per vault, and reversible in one call. ## What you are buying A rate you can advertise, and the spread above it. Your app shows one number, it stays put, and the variance is absorbed by your fee rather than by your user's balance. The mechanism is the fee you already control, moved on your behalf. You stay the admin: you set the target, you set the range the fee may travel in, and you are the only one who can take the vault back out. ## When yield runs above target The fee rises and the surplus is captured as vault fees. Your depositors receive the target, and what the strategies earned above it is yours, minus [the DeFindex share](/intro/fees#how-defindex-is-paid). You set a floor and a ceiling when you sign up, and the fee can never leave that range. The limit is enforced by the contract rather than by us remembering it. Moves are gradual and capped, so one odd reading cannot swing your vault. ## When yield runs below target The fee falls toward your floor, step by step, until it gets there. This can only give back yield the strategies actually produced: at a floor of zero your depositors receive all of it and nothing is charged. If that still leaves you short of the target, the only thing that closes the gap is money you put in. That is a separate product: see [Boost](/products/boost), and in particular what the floor you choose here costs you there. ## What DeFindex can do without you Signing up hands us control of one thing, the fee, and nothing else. Exactly how narrow that is: | Action | Who can do it | | - | - | | Move the fee, inside your bounds | DeFindex or you. Outside the bounds it reverts | | Change the fee bounds | **Only you** | | Change the target | **Only you** | | Upgrade the vault | **Only you** | | Take the vault back out | **Only you** | | Change how any of this works | **Nobody.** The contract cannot be upgraded, by us or by anyone | One thing DeFindex does on its own: move the fee inside the range you set. Everything else needs your signature. ## Custody Depositors' funds never leave the vault and their withdrawals are never frozen. We move the fee inside your range and nothing else, and leaving hands control straight back to you. See [Risks and Audits](/advanced-documentation/risks-and-audits#custody). ## Availability Mainnet only for now, and enabled per account: the endpoints return `403 Forbidden` until the feature is switched on for your API key. [Contact us on Discord](https://discord.gg/aV5jHwmsaj) to enable it. ## Audit Audited by [Runtime Verification](https://runtimeverification.com/audits) in July 2026, together with the boost treasury. See [Risks and Audits](/advanced-documentation/risks-and-audits). > [card] [The endpoints](/integration-guide/stable-apy) > > Register a vault, change the target, exit. # Vaults Source: https://docs.defindex.io/products/vaults The base product. Everything else sits on top of one. A vault is what almost every partner buys, and the only product you need to offer a balance that earns. Your users deposit into it, it puts that money to work, and your app reads back one balance and one APY. ## Several sources, one balance A vault can use several yield sources at once, and adding a new one does not disturb the vaults already running, because each source sits behind its own strategy. See [Strategies](/strategies) for the ones running today. Which sources your vault may use is decided when it is created. No vault function adds or swaps one afterwards, and the only thing that can change the list is replacing the vault's code, which is a decision you make when you create it: a vault can be deployed upgradable or permanent. ## What you control You choose which assets the vault accepts, which sources it may use, and the fee it charges on the yield. The fee you can change whenever you want. See [Fees and revenue](/intro/fees). Money that has not been put to work yet sits in the vault itself, and a user can withdraw it like any other balance. Keeping some there is deliberate: it makes small deposits cheaper to handle, and it is where funds land if we ever need to pull them out of a protocol in a hurry. ## What protects the money * A vault can only ever invest in the sources chosen when it was created. * Nothing can be sent to an outside address. Money moves between the vault and its own strategies, and out only to the user who owns it. * If a protocol underneath turns risky, one call pulls everything back into the vault. * A source can be closed to new money while withdrawals stay open. * No lock-up. A user withdraws whenever they want, with no minimum holding period and no notice, and nobody can freeze it. * Fees only accrue on gains. None of that is policy. It is what the contracts do, and they are public in [defindex-io/stellar-contracts](https://github.com/defindex-io/stellar-contracts). The audit reports are on [Risks and Audits](/advanced-documentation/risks-and-audits). ## Read next * [Fees and revenue](/intro/fees): what you charge and what you keep. * [Quickstart](/integration-guide/quickstart): a working deposit in three commands. * [WhitePaper](/defindex-white-paper-1.0.pdf): how the contracts are built. # Build a strategy Source: https://docs.defindex.io/strategies/build Six methods, and any vault can allocate to your contract. ## What is a strategy? A strategy is a set of **steps** to execute an investment in one or several protocols: holding an asset, farming and auto-compounding rewards, leveraged lending, leveraged farming. A vault does not know any of those steps. It hands assets to a strategy and asks what they are worth now. Everything protocol-specific lives behind [the strategy trait](#the-strategy-trait), which is why a new strategy can be added without touching the vault. For worked examples, see [the strategies running today](/strategies). ## The Strategy Trait A strategy implements [`DeFindexStrategyTrait`](https://github.com/defindex-io/stellar-contracts/blob/main/strategies/core/src/lib.rs). Six methods, and any vault can allocate to your contract. ```toml theme={null} [dependencies] defindex-strategy-core = "0.2.0" ``` ### The six methods | Method | Signature | | - | - | | `__constructor` | `fn __constructor(env: Env, asset: Address, init_args: Vec)` | | `asset` | `fn asset(env: Env) -> Result` | | `deposit` | `fn deposit(env: Env, amount: i128, from: Address) -> Result` | | `withdraw` | `fn withdraw(env: Env, amount: i128, from: Address, to: Address) -> Result` | | `harvest` | `fn harvest(env: Env, from: Address, data: Option) -> Result<(), StrategyError>` | | `balance` | `fn balance(env: Env, from: Address) -> Result` | `from` is always the vault. * **`__constructor`**: the underlying asset plus `init_args`, a free-form `Vec` whose shape you define. Pool addresses, routers, thresholds, the keeper. Validate here. * **`deposit`** and **`withdraw`**: return the vault's balance *after* the operation, not the amount moved. `from.require_auth()` first. * **`balance`**: the vault's position at the live protocol rate. Do not cache the rate. > **The one rule that matters.** `deposit`, `withdraw` and `balance` return **underlying asset**, never internal shares or protocol receipt tokens. The vault prices its dfTokens off that number, so a strategy that returns bTokens gives every user of the vault a wrong share price. **`harvest`** is every active action the position needs: claiming and compounding rewards, adjusting a leverage ratio, rebalancing a drifting position, rolling an expiring one. Deposit and withdraw are driven by the vault; harvest is driven by nobody, which is why it needs a keeper. `data` is an optional opaque blob, by convention a big-endian `i128` minimum amount out so a harvest that swaps cannot be sandwiched. With nothing to do, return `Ok(())` rather than failing. ### Authorization Address-based, through `require_auth()`. The trait defines no roles, but you need one: the **keeper**, the address allowed to call `harvest`. Store it yourself, check it twice, and allow rotation signed by the current keeper. ```rust theme={null} let keeper = storage::get_keeper(&e)?; keeper.require_auth(); if from != keeper { return Err(StrategyError::NotAuthorized); } ``` Every call your strategy makes on its own behalf needs `env.authorize_as_current_contract()` with the matching sub-invocations. Exercise that with real auth in at least one test, not only `mock_all_auths()`. ### Events Emit the ones from [`defindex_strategy_core::event`](https://github.com/defindex-io/stellar-contracts/blob/main/strategies/core/src/event.rs). Indexers, the API and the APY charts read them, so a silent strategy is invisible in the product even when it works. ```rust theme={null} pub struct DepositEvent { pub amount: i128, pub from: Address } pub struct WithdrawEvent { pub amount: i128, pub from: Address } pub struct HarvestEvent { pub amount: i128, pub from: Address, pub price_per_share: i128 } ``` `price_per_share` is what DeFindex computes your APY from. See [Strategies APY](#strategies-apy). ### Errors Return [`StrategyError`](https://github.com/defindex-io/stellar-contracts/blob/main/strategies/core/src/error.rs) rather than panicking: `NotInitialized` (401), `InvalidArgument` (411), `InsufficientBalance` (412), `InvalidSharesMinted` (416), `OnlyPositiveAmountAllowed` (417), `NotAuthorized` (418). ### Share accounting Several vaults can use one strategy at once, so track shares per vault and convert to underlying on the way out. ERC-4626, with the upstream rate refreshed on every touch. * **Rounding direction.** In the protocol's favour on the way in, the user's disfavour on the way out. The other way round leaks value one stroop at a time. * **The inflation attack.** The first depositor can donate assets so later deposits round to zero shares. Burn a small fixed amount of shares on the first deposit, permanently. ### Before you ship * `deposit`, `withdraw` and `balance` return underlying, at the live rate. * `from.require_auth()` on deposit and withdraw, keeper check on harvest. * All three events emitted, with a real `price_per_share`. * First-deposit inflation guard in place. * Rounding tested in both directions. Build to `wasm32v1-none`, optimize with `stellar contract optimize`, and test against the upstream protocol deployed locally rather than a mock of it. The [Blend strategy](https://github.com/defindex-io/stellar-contracts/tree/main/strategies/blend) in the contracts repo does all of the above, and its [tests](https://github.com/defindex-io/stellar-contracts/tree/main/strategies/blend/src/test/blend) cover the inflation and rounding attacks explicitly. ## Strategies APY Every strategy earns differently, so DeFindex does not try to model lending rates, emission schedules and reward prices per protocol. It reads one number off the `HarvestEvent`: the **price per share**. ```rust theme={null} pub struct HarvestEvent { pub amount: i128, pub from: Address, pub price_per_share: i128, } ``` Depositors receive shares. As the strategy earns, each share is worth more underlying. Track that one value over time and the APY falls out, whatever the strategy does inside. Comparing the price per share now against its value $\Delta t$ days ago: $$ \text{ROI} = \frac{\text{PPS}_\text{now}}{\text{PPS}_\text{then}} - 1 $$ $$ \text{APY} = \left(1 + \text{ROI} \right)^{\left(\frac{365.2425}{\Delta t}\right)} - 1 $$ `365.2425` is the average length of a year, leap years included. **Example.** A price per share of `1.10` today against `1.00` thirty days ago is an ROI of `0.10`, which annualizes to $(1.10)^{365.2425/30} - 1 \approx 113.8\%$. This is why [the trait](#the-strategy-trait) insists on emitting `HarvestEvent` with a real `price_per_share`. A strategy that does not is invisible to the APY charts, the API and the indexer. # Gami earnUSDC Autocompound Source: https://docs.defindex.io/strategies/gami-earnusdc Deposits USDC into the curated Gami earnUSDC vault and compounds its Merkl rewards back into it. ## What Gami earnUSDC is [Gami earnUSDC](https://app.upshift.finance/vaults/stellar/gami-earnusdc) is a curated USDC vault on Stellar. [Gami Labs](https://gamilabs.io/), an on-chain asset manager, runs the strategy behind it, on vault infrastructure built by [Upshift](https://docs.upshift.finance/about-upshift). ## Why Gami earnUSDC * **Curated across institutional-grade venues.** Gami allocates the vault's USDC between institutional-grade assets like [Centrifuge's deJTRSY](https://stellar.org/press/centrifuge-brings-derwa-to-stellar-launching-with-usd20m-into-dejtrsy-and-dejaaa), a token backed by a fund of short-term US Treasury bills, lending markets like [Templar](https://www.templarfi.org/) and its protocol on Stellar, [Precept](/strategies/precept-supply), and fixed-rate markets like [Spectra](https://spectra.finance/). The current allocation is on the [vault's page](https://app.upshift.finance/vaults/stellar/gami-earnusdc). * **Institutional custody and policy controls.** Gami operates from [Fordefi](https://fordefi.com/customer-stories/how-gami-labs-curates-institutional-vaults-with-fordefis-policy-engine) MPC wallets with a policy engine, and can only use the protocols and contracts the vault allows. See Upshift's [curator model](https://docs.upshift.finance/vault-architecture/stellar/curator-model). * **No lock-up.** Withdrawals are instant, up to the USDC the vault holds at that moment. * **Rewards on top.** A [Merkl campaign](https://app.merkl.xyz/opportunities/stellar/UPSHIFT_VAULT/CCL3WITWFFXIHV2I52ECV5DPIEOFSTU3PBPR53ILPLF2IP5KHECXRUTY) pays USDC to the vault's depositors. * **Open source and audited.** The vault contracts are [public](https://github.com/upshift-protocol/stellar-upshift-vault-contracts) and audited by Halborn. ## What the strategy does It deposits USDC into the Gami earnUSDC vault and holds the shares. It also harvests the Merkl rewards automatically and deposits them back into the vault, so every depositor's balance grows without claiming anything. No borrowing and no swaps. The yield is the vault's share price plus the compounded rewards. ## Audits * [Halborn, Upshift Stellar Vaults, 2026-04](https://docs.upshift.finance/audits/halborn-2026-04-stellar-vault.pdf): no critical or high findings. The rest are on Upshift's [audits page](https://docs.upshift.finance/resources/audits). # Introduction Source: https://docs.defindex.io/strategies/index What a vault can put the money into. A vault does not know how a lending market or an AMM works. A strategy does. Each one wraps a single yield source and exposes the same six methods to any vault, which is why adding a yield source means writing and auditing one strategy rather than changing the vault every partner already uses. Which strategies a given vault may use is fixed when the vault is created. Deployed addresses are on [Contract Deployments](/contract-deployments/index), and what each one is worth right now is on [defindex.io/strategies](https://www.defindex.io/strategies). > [card] [Precept Supply](/strategies/precept-supply) > > Lends USDC to one isolated Precept market. Supply interest only. > [card] [Gami earnUSDC Autocompound](/strategies/gami-earnusdc) > > Deposits into the curated Gami earnUSDC vault and compounds its Merkl rewards back in. > [card] [Sentora USDC Autocompound](/strategies/sentora-usdc) > > Deposits into the curated Sentora USDC vault and compounds its Merkl rewards back in. > [card] [RWA Wrapper](/strategies/rwa-wrapper) > > Government bond yield for a USDC vault. Users only see USDC. > [card] [K2 Autocompound](/strategies/k2-autocompound) > > Lends on K2 and compounds the rewards back in. Supply only. > [card] [Building one yourself](/strategies/build) > > The strategy trait, its six methods, and how APY is computed. # K2 Autocompound Source: https://docs.defindex.io/strategies/k2-autocompound Lends on K2 and compounds the rewards back in. Supply only, no borrowing. ## What K2 is [K2](https://app.k2lend.com/) is a lending protocol on Stellar, built by Kinetic. Lenders supply an asset such as USDC and earn interest from borrowers, plus rewards paid in other tokens. ## Why K2 Autocompound * **Two sources of yield in one balance.** The interest and the rewards both end up in the asset your users deposited. * **Rewards compound on their own.** Nobody has to claim, sell or reinvest anything. * **Supply only.** The strategy lends. It never borrows, so there is no debt and no liquidation risk on its side. * **Withdrawals are never restricted.** A vault can always exit its position. * **Live and audited.** The strategy runs on mainnet and was audited by Halborn. ## What the strategy does It supplies the vault's asset on K2 and earns interest. On a regular schedule it claims the rewards, swaps them for the same asset on Soroswap and supplies them back, so every depositor's balance grows. ## Audits * [Halborn, Stellar strategies, 2026-09](https://github.com/defindex-io/stellar-contracts/blob/main/docs/audits/2026_09_07_halborn_stellar_strategies_audit.pdf): covers this strategy. Every finding was addressed before the mainnet deployment. * K2's own audits are on its [security page](https://docs.k2lend.com/security-and-audits). The USDC instance is live on mainnet at [`CAOK66QTVE2QXWJPDXDX75ULFKUQDN43AXKYWOBZAERCPZOJL2UEBVJW`](https://stellar.expert/explorer/public/contract/CAOK66QTVE2QXWJPDXDX75ULFKUQDN43AXKYWOBZAERCPZOJL2UEBVJW). All addresses are on [Contract Deployments](/contract-deployments/index). # Precept Supply Source: https://docs.defindex.io/strategies/precept-supply Lends USDC to one isolated Precept lending market. Supply interest only. ![Precept x DeFindex](https://mintcdn.com/defindex/26-c60X50q13liUQ/images/precept-x-defindex.png?fit=max\&auto=format\&n=26-c60X50q13liUQ\&q=85\&s=aeddec4e22a86ad9bbfcfd703cda104b) ## What Precept is [Precept](https://docs.precept.templarfi.org) is [Templar](https://www.templarfi.org/)'s lending protocol on Stellar, [live since 2026-11-09](https://www.templarfi.org/blog/precept) with DeFindex as a launch partner. ## Why Precept * **Isolated markets.** On most lending protocols, every lender in a pool shares the risk of every asset in it. On Precept, one market's risk does not affect another. * **Rules fixed on chain.** Each market's collateral, limits and price feeds are set before launch and readable by anyone. After that, no admin can change parameters, raise caps, swap the oracle or set fees. * **Redundant prices.** An aggregator reads several sources instead of one, with circuit breakers that block a feed when its price moves past set limits. * **No governance-token backstop.** Lenders have no exposure to a token that can lose value the moment it is needed. * **Watched around the clock.** Hypernative monitors every market, and professional liquidators serve each one. ## What the strategy does It supplies USDC to Precept's [XLM/USDC market](https://precept.templarfi.org/markets/CDOU4OEOBWACSNAH7T72IAR4JXJDNS4ZFVHT7TWILVKVBOR3DZT3VSK2) and nothing else: no borrowing, no swaps, no rewards to claim. The yield is the interest borrowers pay, which accrues in the vault's balance. ## Audits * [Guardian, Precept contracts, 2026-10](https://github.com/Templar-Protocol/precept/blob/62c8e9bee072d5e58494c0f7a7bf777926e7ea2b/audits/Guardian%20-%20Templar%20-%20Blend%20Contracts%20V2%20Security%20Review%20-%20October%202026.pdf): no critical, high or medium findings. * Halborn, oracle aggregator, and the Code4rena and Certora audits of the inherited lending core: all on [Precept's security page](https://docs.precept.templarfi.org/security.html). # RWA Wrapper Source: https://docs.defindex.io/strategies/rwa-wrapper Government bond yield for a USDC vault. Deposits and withdrawals stay in USDC. ## What an RWA is A real-world asset (RWA) here is a government bond, or a fund of them, issued as a token. Examples are the [Etherfuse](https://www.etherfuse.com/) stablebonds (CETES, USTRY, TESOURO), [Ondo](https://ondo.finance/) USDY and [Centrifuge's deJTRSY](https://stellar.org/press/centrifuge-brings-derwa-to-stellar-launching-with-usd20m-into-dejtrsy-and-dejaaa), a token backed by a fund of short-term US Treasury bills. The token's price rises as the bonds pay interest. ## Why the RWA Wrapper * **Yield from government bonds.** The return comes from sovereign debt, not from crypto lending markets. * **Your users only see USDC.** They deposit USDC and withdraw USDC. They never hold or trade a bond token. * **Nothing to claim.** There is no reward token. The yield is the bond's price going up. * **Two price checks.** The bond is valued from a price oracle and from the live market. If the two disagree, the operation stops instead of using a wrong price. * **Withdrawals are never paused.** Deposits can be paused. Withdrawals cannot. ## What the strategy does It buys the bond token with the vault's USDC on a decentralized exchange and holds it. On a withdrawal it sells just enough of the bond back to USDC. The USDC that comes out is worth more than the USDC that went in, and that difference is the yield. Each deployment holds one bond token. How much it can hold depends on how liquid that bond is on the exchange, so every deployment has a cap per deposit and a cap on its total size. ## Audits * [Halborn, Stellar strategies, 2026-09](https://github.com/defindex-io/stellar-contracts/blob/main/docs/audits/2026_09_07_halborn_stellar_strategies_audit.pdf): covers this strategy. Every finding was addressed before the mainnet deployment. Deployed addresses are on [Contract Deployments](/contract-deployments/index). # Sentora USDC Autocompound Source: https://docs.defindex.io/strategies/sentora-usdc Deposits USDC into the curated Sentora USDC vault and compounds its Merkl rewards back into it. ## What Sentora USDC is [Sentora USDC](https://app.upshift.finance/vaults/stellar/sentora-usdc) is a curated USDC vault on Stellar. [Sentora](https://sentora.com/), an institutional DeFi firm, runs the strategy behind it, on vault infrastructure built by [Upshift](https://docs.upshift.finance/about-upshift). ## Why Sentora USDC * **Curated by an institutional manager.** Sentora curates vaults for institutions, including [Kraken's DeFi Earn](https://sentora.com/case-studies/kraken-defi-earn-vaults-curated-by-sentora-hit-500m-deposits-milestone-in-under-6-months) program. * **Bounded by a policy engine.** The curator can only use the protocols and contracts the vault allows. See Upshift's [curator model](https://docs.upshift.finance/vault-architecture/stellar/curator-model). * **Rewards on top.** A [Merkl campaign](https://app.merkl.xyz/opportunities/stellar/UPSHIFT_VAULT/CALFCZ4TY2CLHDHNJWCZX6JKYGUPV7P3GNQ3UVABXNE5JCV2E774APUM) pays USDC to the vault's depositors. * **Open source and audited.** The vault contracts are [public](https://github.com/upshift-protocol/stellar-upshift-vault-contracts) and audited by Halborn. ## What the strategy does It deposits USDC into the Sentora USDC vault and holds the shares. It also harvests the Merkl rewards automatically and deposits them back into the vault, so every depositor's balance grows without claiming anything. No borrowing and no swaps. The yield is the vault's share price plus the compounded rewards. Withdrawals follow the vault's own terms, listed on the [vault's page](https://app.upshift.finance/vaults/stellar/sentora-usdc). ## Audits * [Halborn, Upshift Stellar Vaults, 2026-04](https://docs.upshift.finance/audits/halborn-2026-04-stellar-vault.pdf): no critical or high findings. The rest are on Upshift's [audits page](https://docs.upshift.finance/resources/audits). # WhitePaper Source: https://docs.defindex.io/whitepaper DeFindex White Paper 1.0 (2024): the protocol design behind the factory, vaults and strategies. The DeFindex White Paper 1.0 (PaltaLabs, 2024) describes the protocol as first designed: the factory, vault, strategy and zapper contracts, the roles that manage a vault, how rates and APY are computed, and the prior art it learned from. It is a frozen, dated document. Where it and these docs disagree, the docs describe the protocol as it runs today. > [card] [DeFindex White Paper 1.0 (PDF)](https://www.defindex.io/defindex-whitepaper-1.0.pdf) > > Download or open the full white paper.