Skip to content

Commit

Permalink
Merge pull request #192 from paltalabs/feat/typescript-package
Browse files Browse the repository at this point in the history
typescript package ready and published
  • Loading branch information
joaquinsoza authored Nov 15, 2024
2 parents 16e4d71 + a4fea65 commit 9c6724b
Show file tree
Hide file tree
Showing 13 changed files with 458 additions and 8,167 deletions.
28 changes: 27 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -143,4 +143,30 @@ Then, you will need to open a terminal connected to the container and run the fo
```sh
curl http://localhost:33791/?code...
```
This will log you in and you can publish the package.
This will log you in and you can publish the package.

## TypeScript SDK Development

See the [TypeScript SDK README](./packages/defindex-sdk/README.md) for more information.

You can use the defindex-soroban container to develop the SDK.
```sh
bash run.sh --nb
```
Then, move to the folder `packages/defindex-sdk`.

### Publish TypeScript SDK
Inside the container, on the `defindex-sdk` folder, run:
```sh
# Login to npm
npm login

# Install dependencies
yarn install

# Build the package
yarn build

# Publish to npm
npm publish --access public
```
46 changes: 46 additions & 0 deletions apps/docs/05-developer-guides/02-typescript-sdk.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# TypeScript SDK

The TypeScript SDK provides a simple way to interact with DeFindex vaults in your web applications. You can easily integrate vault functionality with just **a few lines of code**. The SDK handles all the complexities of Soroban contract interactions while providing a type-safe interface.

## Getting Started

1. **Install the SDK**
```bash
npm install defindex-sdk
# or
yarn add defindex-sdk
```

2. **Import and Initialize**
```typescript
import { Vault, SorobanNetwork } from 'defindex-sdk';

const vault = new Vault({
network: SorobanNetwork.TESTNET,
contractId: 'YOUR_VAULT_CONTRACT_ID'
});
```

3. **Use Vault Functions**
```typescript
// Check balance
const balance = await vault.balance(accountAddress, sorobanContext);

// Make a deposit
const txHash = await vault.deposit(
accountAddress,
100,
true,
sorobanContext,
secretKey // Optional secret key for signing, if you are using a connected wallet it's not needed
);

// Withdraw funds
const withdrawTxHash = await vault.withdraw(
accountAddress,
50,
true,
sorobanContext,
secretKey // Optional secret key for signing, if you are using a connected wallet it's not needed
);
```
21 changes: 21 additions & 0 deletions packages/defindex-sdk/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2024 PaltaLabs

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
139 changes: 139 additions & 0 deletions packages/defindex-sdk/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
# DeFindex SDK

A TypeScript SDK for interacting with DeFindex Vaults on the Stellar Soroban network. DeFindex is a protocol for creating and managing multi-asset investment vaults with customizable strategies.

## Overview

DeFindex Vaults serve as the core of the DeFindex platform, responsible for:
- Managing multiple assets
- Executing investment strategies
- Ensuring proper asset rebalancing
- Minting/burning dfTokens (vault shares)

## Installation

```bash
npm install defindex-sdk
# or
yarn add defindex-sdk

```

## Quick Start

```typescript
import { Vault, SorobanNetwork } from 'defindex-sdk';

// Initialize a vault instance
const vault = new Vault({
network: SorobanNetwork.TESTNET,
contractId: 'YOUR_VAULT_CONTRACT_ID'
});

// Deposit assets
const txHash = await vault.deposit(
accountAddress,
100, // amount
true, // signAndSend
sorobanContext,
secretKey
);
```

## Features

- **Asset Management**: Deposit and withdraw multiple assets
- **Balance Tracking**: Monitor your vault share balance
- **Transaction Handling**: Built-in support for Soroban transactions
- **Type Safety**: Full TypeScript support

## API Reference

### `Vault`

The main class for interacting with DeFindex vaults.

#### Constructor

```typescript
new Vault({
network: SorobanNetwork,
contractId: string
})
```

#### Methods

##### `deposit(account: string, amount: number, signAndSend: boolean, sorobanContext: SorobanContextType, secretKey?: string): Promise<string>`

Deposits assets into the vault and receives dfTokens in return.

- **Parameters:**
- `account`: The depositor's address
- `amount`: Amount to deposit
- `signAndSend`: Whether to sign and submit the transaction
- `sorobanContext`: Soroban context object
- `secretKey`: Optional secret key for signing

- **Returns:** Transaction hash

##### `withdraw(account: string, amount: number, signAndSend: boolean, sorobanContext: SorobanContextType, secretKey?: string): Promise<string>`

Withdraws assets from the vault by burning dfTokens.

- **Parameters:**
- `account`: The withdrawer's address
- `amount`: Amount of dfTokens to burn
- `signAndSend`: Whether to sign and submit the transaction
- `sorobanContext`: Soroban context object
- `secretKey`: Optional secret key for signing

- **Returns:** Transaction hash

##### `balance(account: string, sorobanContext: SorobanContextType): Promise<number>`

Checks the dfToken balance of an account.

- **Parameters:**
- `account`: The account address
- `sorobanContext`: Soroban context object

- **Returns:** Balance amount

## Example Usage

```typescript
import { Vault, SorobanNetwork } from 'defindex-sdk';

async function main() {
// Initialize vault
const vault = new Vault({
network: SorobanNetwork.TESTNET,
contractId: 'YOUR_CONTRACT_ID'
});

// Create Soroban context
const sorobanContext = await createSorobanContext();

// Check initial balance
const balance = await vault.balance(accountAddress, sorobanContext);
console.log('Balance:', balance);

// Deposit assets
const txHash = await vault.deposit(
accountAddress,
100,
true,
sorobanContext,
secretKey
);
console.log('Deposit TX:', txHash);
}
```

For a complete example, see [vault-example.ts](./examples/vault-example.ts).


## Support

- Discord: [Join our community](https://discord.gg/ftPKMPm38f)
89 changes: 89 additions & 0 deletions packages/defindex-sdk/examples/vault-example.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import { Vault, SorobanNetwork } from '../src/Vault';
import { SorobanRpc, Networks, Keypair } from '@stellar/stellar-sdk';

async function createSorobanContext() {
const server = new SorobanRpc.Server("https://soroban-testnet.stellar.org", {
allowHttp: true
});

const secretKey = 'SC352W6PEHWSHYKP5IYO3HWAEVGLTVLZW5WE3UXPWSGKBST5K6DKRT7F';
const keypair = Keypair.fromSecret(secretKey);

return {
server,
address: keypair.publicKey(),
activeChain: {
networkPassphrase: Networks.TESTNET,
network: "TESTNET",
id: "testnet",
networkUrl: "https://soroban-testnet.stellar.org"
},
activeConnector: undefined,
chains: [],
connectors: [],
connect: async () => { },
disconnect: async () => { }
};
}

async function vaultExample() {
const sorobanContext = await createSorobanContext();
const secretKey = 'SC352W6PEHWSHYKP5IYO3HWAEVGLTVLZW5WE3UXPWSGKBST5K6DKRT7F';

// Initialize the Vault
const vault = new Vault({
network: SorobanNetwork.TESTNET,
contractId: 'CAJVX4P2XDRVIGZ7GRHRSGBE6B23L4FQLT5SGUBHU7NT2IER7R2WIURG' // Replace with your contract ID
});

try {
const accountAddress = sorobanContext.address;
console.log('Using account:', accountAddress);

// Check initial balance
const initialBalance = await vault.balance(accountAddress, sorobanContext);
console.log('Initial balance:', initialBalance);

// Deposit 100 tokens
const depositTx = await vault.deposit(
accountAddress,
100,
true,
sorobanContext,
secretKey
);
console.log('Deposit transaction hash:', depositTx);

// Wait a few seconds for the transaction to be processed
await new Promise(resolve => setTimeout(resolve, 5000));

// Check updated balance
const updatedBalance = await vault.balance(accountAddress, sorobanContext);
console.log('Updated balance:', updatedBalance);

// Withdraw 50 tokens
const withdrawTx = await vault.withdraw(
accountAddress,
50,
true,
sorobanContext,
secretKey
);
console.log('Withdraw transaction hash:', withdrawTx);

// Wait a few seconds for the transaction to be processed
await new Promise(resolve => setTimeout(resolve, 5000));

// Check final balance
const finalBalance = await vault.balance(accountAddress, sorobanContext);
console.log('Final balance:', finalBalance);

} catch (error) {
console.error('Error:', error);
}
}

// Execute the example
vaultExample()
.then(() => console.log('Example completed'))
.catch(error => console.error('Example failed:', error));
29 changes: 24 additions & 5 deletions packages/defindex-sdk/package.json
Original file line number Diff line number Diff line change
@@ -1,21 +1,40 @@
{
"name": "defindex-sdk",
"version": "0.1.0",
"repository": "https://github.com/paltalabs/defindex.git",
"version": "0.1.2",
"description": "TypeScript SDK for interacting with DeFindex Vaults on the Stellar Soroban network",
"type": "module",
"repository": {
"type": "git",
"url": "https://github.com/paltalabs/defindex.git"
},
"author": "coderipper <[email protected]>",
"license": "MIT",
"keywords": [
"defindex",
"stellar",
"soroban",
"blockchain",
"sdk"
],
"scripts": {
"build": "tsdx build",
"docs": "typedoc",
"test": "jest"
"test": "jest",
"example": "node --loader ts-node/esm examples/vault-example.ts",
"prepublishOnly": "npm run build"
},
"private": false,
"files": [
"dist"
"dist",
"README.md",
"LICENSE"
],
"module": "dist/defindex-sdk.esm.js",
"main": "dist/index.js",
"typings": "dist/index.d.ts",
"dependencies": {
"@soroban-react/contracts": "^9.1.13",
"@soroban-react/core": "^9.1.13",
"@stellar/stellar-sdk": "^12.1.0"
},
"devDependencies": {
Expand All @@ -30,4 +49,4 @@
"typedoc": "^0.26.4",
"typescript": "5.5.3"
}
}
}
Loading

0 comments on commit 9c6724b

Please sign in to comment.