Skip to content

Commit

Permalink
Merge branch 'main' of https://github.com/paltalabs/defindex into fea…
Browse files Browse the repository at this point in the history
…t/implementChangeFeeReciever
  • Loading branch information
MattPoblete committed Nov 18, 2024
2 parents 5515b72 + c0e3a43 commit ac06f46
Show file tree
Hide file tree
Showing 24 changed files with 633 additions and 8,222 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
```
4 changes: 2 additions & 2 deletions apps/contracts/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
"typescript": "^5.3.3"
},
"dependencies": {
"@stellar/stellar-sdk": "^12.2.0",
"@stellar/stellar-sdk": "^13.0.0",
"dotenv": "^16.4.5"
}
}
}
2 changes: 1 addition & 1 deletion apps/contracts/src/deploy_factory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ export async function deployContracts(addressBook: AddressBook) {
const factoryInitParams: xdr.ScVal[] = [
new Address(loadedConfig.admin.publicKey()).toScVal(),
new Address(defindexReceiver.publicKey()).toScVal(),
nativeToScVal(100, {type: "u32"}),
nativeToScVal(50, {type: "u32"}),
nativeToScVal(Buffer.from(addressBook.getWasmHash("defindex_vault"), "hex")),
];

Expand Down
7 changes: 5 additions & 2 deletions apps/contracts/src/deploy_hodl.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Address, nativeToScVal, xdr, Asset, Networks } from "@stellar/stellar-sdk";
import { Address, Asset, Networks, xdr } from "@stellar/stellar-sdk";
import { AddressBook } from "./utils/address_book.js";
import {
airdropAccount,
Expand Down Expand Up @@ -45,14 +45,17 @@ export async function deployContracts(addressBook: AddressBook) {
const xlmAddress = new Address(xlmContractId);
const xlmScVal = xlmAddress.toScVal();

const soroswapUSDC = new Address("CAAFIHB4I7WQMJMKC22CZVQNNX7EONWSOMT6SUXK6I3G3F6J4XFRWNDI");
const usdcScVal = soroswapUSDC.toScVal();

const emptyVecScVal = xdr.ScVal.scvVec([]);

console.log("Initializing DeFindex HODL Strategy");
await invokeContract(
"hodl_strategy",
addressBook,
"initialize",
[xlmScVal, emptyVecScVal],
[usdcScVal, emptyVecScVal],
loadedConfig.admin
);
}
Expand Down
5 changes: 2 additions & 3 deletions apps/contracts/src/utils/contract.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
// import { randomBytes } from 'crypto';
import {
Address,
Asset,
Expand Down Expand Up @@ -195,7 +194,7 @@ export async function bumpContractInstance(
txBuilder.addOperation(Operation.extendFootprintTtl({ extendTo: 535670 })); // 1 year
txBuilder.setSorobanData(bumpTransactionData);
const result = await invokeTransaction(txBuilder.build(), source, false);
// @ts-expect-error console.log(status)
//@ts-ignore
console.log(result.status, "\n");
}

Expand Down Expand Up @@ -231,7 +230,7 @@ export async function bumpContractCode(
txBuilder.addOperation(Operation.extendFootprintTtl({ extendTo: 535670 })); // 1 year
txBuilder.setSorobanData(bumpTransactionData);
const result = await invokeTransaction(txBuilder.build(), source, false);
// @ts-expect-error console.log(status)
//@ts-ignore
console.log(result.status, "\n");
}

Expand Down
8 changes: 4 additions & 4 deletions apps/contracts/src/utils/env_config.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Horizon, Keypair, SorobanRpc } from "@stellar/stellar-sdk";
import { Horizon, Keypair, rpc } from "@stellar/stellar-sdk";
import dotenv from "dotenv";
import * as fs from "fs";
import path from "path";
Expand All @@ -23,14 +23,14 @@ interface Config {
}

class EnvConfig {
rpc: SorobanRpc.Server;
rpc: rpc.Server;
horizonRpc: Horizon.Server;
passphrase: string;
friendbot: string | undefined;
admin: Keypair;

constructor(
rpc: SorobanRpc.Server,
rpc: rpc.Server,
horizonRpc: Horizon.Server,
passphrase: string,
friendbot: string | undefined,
Expand Down Expand Up @@ -92,7 +92,7 @@ class EnvConfig {
const allowHttp = network === "standalone";

return new EnvConfig(
new SorobanRpc.Server(rpc_url, { allowHttp }),
new rpc.Server(rpc_url, { allowHttp }),
new Horizon.Server(horizon_rpc_url, { allowHttp }),
passphrase,
friendbot_url,
Expand Down
14 changes: 7 additions & 7 deletions apps/contracts/src/utils/tx.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
import {
Account,
Keypair,
SorobanRpc,
rpc,
Transaction,
TransactionBuilder,
xdr,
} from "@stellar/stellar-sdk";
import { config } from "./env_config.js";

type txResponse =
| SorobanRpc.Api.SendTransactionResponse
| SorobanRpc.Api.GetTransactionResponse;
| rpc.Api.SendTransactionResponse
| rpc.Api.GetTransactionResponse;
type txStatus =
| SorobanRpc.Api.SendTransactionStatus
| SorobanRpc.Api.GetTransactionStatus;
| rpc.Api.SendTransactionStatus
| rpc.Api.GetTransactionStatus;

const network = process.argv[2];
const loadedConfig = config(network);
Expand Down Expand Up @@ -50,7 +50,7 @@ export async function invokeTransaction(
// simulate the TX
console.log(tx.toXDR());
const simulation_resp = await loadedConfig.rpc.simulateTransaction(tx);
if (SorobanRpc.Api.isSimulationError(simulation_resp)) {
if (rpc.Api.isSimulationError(simulation_resp)) {
// No resource estimation available from a simulation error. Allow the response formatter
// to fetch the error.
console.log("simulation_resp", simulation_resp);
Expand All @@ -72,7 +72,7 @@ export async function invokeTransaction(
txResources.writeBytes()
)
.build();
const assemble_tx = SorobanRpc.assembleTransaction(tx, simulation_resp);
const assemble_tx = rpc.assembleTransaction(tx, simulation_resp);
sim_tx_data.resourceFee(
xdr.Int64.fromString(
(Number(sim_tx_data.resourceFee().toString()) + 100000).toString()
Expand Down
5 changes: 3 additions & 2 deletions apps/dapp/app/page.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
"use client";
import { Container, HStack } from '@chakra-ui/react'
import { HStack } from '@chakra-ui/react'
import { useSorobanReact } from '@soroban-react/core'
import ManageVaults from '@/components/ManageVaults/ManageVaults';
import { TestTokens } from '@/components/TestTokens';
import {
Chart as ChartJS,
ArcElement,
Chart as ChartJS,
} from 'chart.js';

ChartJS.register(ArcElement);
Expand Down
37 changes: 18 additions & 19 deletions apps/dapp/src/components/DeployVault/AddNewStrategyButton.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,17 @@
'use client'
import React from 'react'
import { useEffect, useState } from 'react'
import {
DialogBackdrop,
DialogBody,
DialogContent,
DialogFooter,
DialogRoot,
DialogTrigger,
} from '@/components/ui/dialog'
import { getTokenSymbol } from '@/helpers/getTokenInfo'
import { StrategyMethod, useStrategyCallback } from '@/hooks/useStrategy'
import { getDefaultStrategies, pushAmount, pushAsset } from '@/store/lib/features/vaultStore'
import { useAppDispatch } from '@/store/lib/storeHooks'
import { Asset, Strategy } from '@/store/lib/types'
import {
Button,
For,
Expand All @@ -12,25 +23,13 @@ import {
Stack,
Text,
} from '@chakra-ui/react'
import { MdAdd } from 'react-icons/md'
import {
DialogBackdrop,
DialogBody,
DialogContent,
DialogFooter,
DialogRoot,
DialogTrigger,
} from '@/components/ui/dialog'
import { useAppDispatch, useAppSelector } from '@/store/lib/storeHooks'
import { getDefaultStrategies, pushAmount, pushAsset } from '@/store/lib/features/vaultStore'
import { useSorobanReact } from '@soroban-react/core'
import { Asset, Strategy } from '@/store/lib/types'
import { CheckboxCard } from '../ui/checkbox-card'
import { getTokenSymbol } from '@/helpers/getTokenInfo'
import { StrategyMethod, useStrategyCallback } from '@/hooks/useStrategy'
import { scValToNative, xdr } from '@stellar/stellar-sdk'
import { InputGroup } from '../ui/input-group'
import { useEffect, useState } from 'react'
import { MdAdd } from 'react-icons/md'
import { Checkbox } from '../ui/checkbox'
import { CheckboxCard } from '../ui/checkbox-card'
import { InputGroup } from '../ui/input-group'

interface AmountInputProps {
amount: number
Expand Down Expand Up @@ -151,7 +150,7 @@ function AddNewStrategyButton() {
size="md"
textAlign={'end'}
disabled={defaultStrategies.length === 0}>
Add new assets
Add Strategy
</Button>
</DialogTrigger>
<DialogContent>
Expand Down
98 changes: 98 additions & 0 deletions apps/dapp/src/components/TestTokens.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import { useSorobanReact } from "@soroban-react/core";

import { HStack, Text } from "@chakra-ui/react";
import { contractInvoke } from "@soroban-react/contracts";
import { Address, Keypair, nativeToScVal, scValToNative, xdr } from "@stellar/stellar-sdk";
import { useEffect, useState } from "react";
import { Button } from "./ui/button";

export const TestTokens = () => {
const sorobanContext = useSorobanReact();
const { address, activeChain, server } = sorobanContext;
const networkPassphrase = activeChain?.networkPassphrase ?? '';
const [isSubmitting, setSubmitting] = useState(false);
const [balance, setBalance] = useState<string>("0");

const testnetUSDC = "CAAFIHB4I7WQMJMKC22CZVQNNX7EONWSOMT6SUXK6I3G3F6J4XFRWNDI";
const admin_account = Keypair.fromSecret(
process.env.NEXT_PUBLIC_TEST_TOKENS_ADMIN as string,
);

const fetchBalance = async () => {
if (!address) return;
contractInvoke({
contractAddress: testnetUSDC,
method: 'balance',
args: [new Address(address).toScVal()],
sorobanContext,
signAndSend: false,
}).then((result) => {
let balance = scValToNative(result as xdr.ScVal);
balance = BigInt(BigInt(balance) / BigInt(1e7)).toString();
setBalance(balance);

}).catch ((error) => {
console.log('🚀 « error:', error);
})
}

useEffect(() => {
fetchBalance();
}, [address])

const handleMint = async () => {
console.log("Minting");
setSubmitting(true);

const amount = 1000000000000

let adminSource;

try {
adminSource = await server?.getAccount(admin_account.publicKey());
} catch (error) {
alert('Your wallet or the token admin wallet might not be funded');
setSubmitting(false);
return;
}

if (!address) {
return;
}
if (!adminSource) {
return;
}

try {
let result = await contractInvoke({
contractAddress: testnetUSDC,
method: 'mint',
args: [new Address(address).toScVal(), nativeToScVal(amount, {type: 'i128'})],
sorobanContext,
signAndSend: true,
secretKey: admin_account.secret(),
});
if (result) {
fetchBalance();
}
} catch (error) {
console.log('🚀 « error:', error);
}

setSubmitting(false);
}

return (
<HStack>
<Text>Current Balance: {balance} USDC</Text>
<Button
rounded={18}
onClick={handleMint}
loadingText="Minting..."
loading={isSubmitting}
>
Mint test USDC
</Button>
</HStack>
);
};
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
);
```
Loading

0 comments on commit ac06f46

Please sign in to comment.