Velvet-Capital / 3rd-party-integration

0 stars 0 forks source link

Velvet Intents API Docs #2

Open NikhilSharma03 opened 3 weeks ago

NikhilSharma03 commented 3 weeks ago

Velvet Intents API

Welcome to the Velvet Intents API documentation! This API provides a efficient way to trade assets within your Velvet vaults programmatically. Designed for flexibility and ease of integration, the API allows you to automate trading activities.

Dive into this documentation to get started on exploring key endpoints, and discovering how to optimize your trading experience on Velvet Vaults.

Trade Steps

There are three steps to trade assets programmatically

  1. Fetch All Created Vaults
  2. Using Rebalance API Endpoint
  3. Executing the trade

Fetch All Created Vaults

To retrieve all created vaults associated with a specific owner wallet on Velvet V3, use the following endpoint:

HTTP Request:

curl -X GET "https://api.velvet.capital/api/v3/portfolio/owner/<OWNER_WALLET_ADDRESS>?chain=base"

Parameters:

Response Schema:

The response will contain a JSON object with the details of all portfolios created by the specified wallet on Velvet V3.

{
  "data": [
    {
      "portfolioId": string,
      "portfolio": string,
      "name": string,
      "symbol": string,
      "public": boolean,
      "initialized": boolean,
      "confirmed": boolean,
      "tokenExclusionManager": string,
      "rebalancing": string,                   <----- **WE WOULD NEED THIS ADDRESS IN NEXT STEPS**
      "owner": string,
      "assetManagementConfig": string,
      "accessController": string,
      "feeModule": string,
      "vaultAddress": string,
      "gnosisModule": string,
      "whitelistedUsers": [],
      "whitelistedTokens": [],
      "whitelistAccessGrantedUsers": [],
      "assetManagerAccessGrantedUsers": [],
      "chainID": 8453,
      "chainName": "base",
      "txnHash": string,
      "createdAt": Date,
      "updatedAt": Date,
      "creatorName": string,
      "description": string,
      "avatar": string
    },
    ...
  ]
}

Using Rebalance API Endpoint

In this step, the Rebalance API endpoint is utilized to retrieve essential call data and other necessary inputs required to execute trades within a vault.

HTTP Request:

curl -X POST "https://eventsapi.velvetdao.xyz/api/v3/rebalance" \
     -H "Content-Type: application/json" \
     -d '{
          "rebalanceAddress": "",
          "sellToken": "",
          "buyToken": "",
          "sellAmount": "",
          "slippage": "",
          "remainingTokens": [
            ""
          ],
          "owner": ""
        }'

Parameters:

Note: The sellAmount should be specified in a big number format based on the token's decimal. For example: 1 USDC, the value would be "1000000" since USDC is 6 decimal token.

Note: Assuming a fund only has USDC in the vault. After trading 50% amount of USDC to WETH, the fund will now have both USDC and WETH tokens. So in this case the remainingTokens would be array of both of these tokens addresses.

Response Schema:

The response will contain a JSON object that includes the trade details necessary for the final step of the process.

{
  "newTokens": [string],
  "sellTokens": [string],
  "sellAmounts": [string],
  "handler": string,
  "callData": string,
  "estimateGas": string,
  "gasPrice": string
}

Executing the trade

In this final step, we will leverage the trade data obtained from the previous step to execute the trade.

To get started, you need to install the Ethers.js library.

npm install ethers@5.5.4

Using the contract ABI and rebalancing address, you can create an instance of the Rebalance contract and execute the trade:

import ethers from 'ethers' // use "type": "module" in package.json

const provider = new ethers.providers.JsonRpcProvider('') // use chainlist for public RPC's

const privateKey = '' // Replace with owner wallet's private key

const wallet = new ethers.Wallet(privateKey, provider)

export const RebalanceABI = [
  {
    inputs: [
      {
        components: [
          {
            internalType: 'address[]',
            name: '_newTokens',
            type: 'address[]',
          },
          {
            internalType: 'address[]',
            name: '_sellTokens',
            type: 'address[]',
          },
          {
            internalType: 'uint256[]',
            name: '_sellAmounts',
            type: 'uint256[]',
          },
          {
            internalType: 'address',
            name: '_handler',
            type: 'address',
          },
          {
            internalType: 'bytes',
            name: '_callData',
            type: 'bytes',
          },
        ],
        internalType: 'struct FunctionParameters.RebalanceIntent',
        name: 'rebalanceData',
        type: 'tuple',
      },
    ],
    name: 'updateTokens',
    outputs: [],
    stateMutability: 'nonpayable',
    type: 'function',
  },
]

const RebalanceInstance = new ethers.Contract(
  'VAULT REBALANCING ADDRESS',
  RebalanceABI,
  wallet
)

async function executeRebalance() {
  try {
    console.log('Executing Trade...')

    const contractData = await RebalanceInstance.updateTokens(
      {
        _newTokens: newTokens, // from response object of rebalance api
        _sellTokens: sellTokens, // from response object of rebalance api
        _sellAmounts: sellAmounts, // from response object of rebalance api
        _handler: handler, // from response object of rebalance api
        _callData: callData, // from response object of rebalance api
      },
      {
        gasLimit: ethers.BigNumber.from(estimateGas).add('1000000'),
        gasPrice: gasPrice,
      }
    )

    console.log('Transaction successful:', contractData)
  } catch (error) {
    console.error('Transaction failed:', error)
  }
}

executeRebalance()

That's it! You can follow these steps to execute trade for other vaults. Happy coding! 🎉

omkar199 commented 1 day ago

Deposit Portfolio API

Endpoint:
POST /api/v3/portfolio/deposit

Base URL:
https://eventsapi.velvetdao.xyz


Description

This endpoint allows a user to deposit a specified amount of tokens into a portfolio.


Headers

| Header Name | Value | Description | |---------------|-------------------|-----------------------------------| | `accept` | `application/json` | Specifies the accepted response format. | | `Content-Type`| `application/json` | Specifies the request payload format. | Response The API will return a JSON response with details of the deposit status. | Parameter | Type | Required | Description | |----------------|----------|----------|-------------------------------------------------------------------------| | `portfolio` | `string` | Yes | The portfolio contract address to deposit into (Ethereum address). | | `depositAmount`| `number` | Yes | The amount to deposit. | | `depositToken` | `string` | Yes | The contract address of the token being deposited (Ethereum address). | | `user` | `string` | Yes | The Ethereum address of the user making the deposit. | | `depositType` | `string` | Yes | Specifies the type of deposit (batch, single, etc.). | | `tokenType` | `string` | Yes | Specifies the token type (erc20, erc721, etc.). | Request body: ``` { "portfolio": "0x444ef5b66f3dc7f3d36fe607f84fcb2f3a666902", "depositAmount": 1, "depositToken": "0x50c5725949A6F0c72E6C4a641F24049A917DB0Cb", "user": "0x3C96e2Fc58332746fbBAB5eC44f01572F99033ed", "depositType": "batch", "tokenType": "erc20" } ``` Response (Output of request) : ``` const tx = { "to": "0xe4e23120a38c4348D7e22Ab23976Fa0c4Bf6e2ED", "data": "0x9136d415000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000648a6a1e850000000000000000000000004621b7a9c75199271f773ebd9a499dbd165c3191000000000000000000000000d9686d2834349e3fd507919a8fba420b2f40004e0000ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000020cab6eed08a191c4c2459daf", "gasLimit": "18000000", "gasPrice": "21719976" } ``` ``` import { Wallet, providers } from "ethers"; // Ensure environment variables are set if (!process.env.RPC_URL || !process.env.PRIVATE_KEY) { throw new Error("Missing required environment variables: RPC_URL or PRIVATE_KEY"); } // Load RPC URL and private key securely const rpcUrl = process.env.RPC_URL; const privateKey = process.env.PRIVATE_KEY; // Create a JSON RPC provider const provider = new providers.JsonRpcProvider(rpcUrl); // Initialize a wallet instance const wallet = new Wallet(privateKey, provider); async function main() { try { // Fetch the current gas price const gasPrice = await provider.getGasPrice(); console.log("Current gas price:", gasPrice.toString()); //tx from api response // Send the transaction const transactionResponse = await wallet.sendTransaction(tx); console.log("Transaction Response:", transactionResponse); // Wait for the transaction to be mined const receipt = await transactionResponse.wait(); console.log("Transaction Receipt:", receipt); } catch (error) { console.error("Error occurred while sending the transaction:", error); } } // Execute the main function main(); ```