Skip to content

Commit

Permalink
Feat [SB-167]: fix demo page (#7)
Browse files Browse the repository at this point in the history
  • Loading branch information
dblackstone1 authored Nov 27, 2023
1 parent db3d0ca commit 4c0449b
Show file tree
Hide file tree
Showing 8 changed files with 364 additions and 215 deletions.
30 changes: 30 additions & 0 deletions .github/workflows/deploy.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
name: Build and Deploy
on:
push:
branches:
- main

jobs:
build-and-deploy:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v2

- name: Install Node.js
uses: actions/setup-node@v2
with:
node-version: '20.9.0'

- name: Install Dependencies
run: npm install

- name: Build
run: npm run build

- name: Deploy
uses: JamesIves/github-pages-deploy-action@v4
with:
branch: main
folder: build
token: ${{ secrets.GITHUB_TOKEN }}
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
{
"name": "orchestralabs",
"version": "0.1.0",
"proxy": "http://localhost:8080",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
Expand Down
154 changes: 154 additions & 0 deletions src/api/api.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
import { BASE_URL } from "../config/config";

export const fetchDemoData = async () => {
try {
const response = await fetch(`${BASE_URL}/demodata`);
const data = await response.json();
return data;
} catch (error) {
console.error('Error fetching wallet data:', error);
throw error;
}
};

export const fetchWalletBalances = async (address) => {
try {
const response = await fetch(`${BASE_URL}/wallets/balance?wallet_address=${address}`);
const data = await response.json();
return data.total_amounts || {};
} catch (error) {
console.error('Error fetching wallet balance:', error);
throw error;
}
};

export const changeExchangeRatioApi = async (newRatio) => {
try {
const response = await fetch(`${BASE_URL}/changeExchangeRatio?percentage=${newRatio}`, {
method: 'POST',
});
if (!response.ok) {
throw new Error('Network response was not ok');
}
const data = await response.json();
return { success: true, data: data };
} catch (error) {
console.error('Error changing exchange ratio:', error);
return { success: false, error: error };
}
};

export const getMaxSendableAmount = async (walletAddress) => {
if (!walletAddress) {
return { error: 'No wallet address provided.' };
}

try {
// Fetch current wallet balance
const walletBalanceResponse = await fetch(`${BASE_URL}/wallets/balance?wallet_address=${walletAddress}`).then(res => res.json());

// Fetch current transaction fees (as percentages)
const feeResponse = await fetch('/transactions/fees').then(res => res.json());
const minerFeePercent = feeResponse.miner_fee.amount;
const reserveFeePercent = feeResponse.reserve_fee.amount;

// Calculate total fee factor (1 + sum of fee percentages)
const totalFeeFactor = 1 + minerFeePercent + reserveFeePercent;

// Calculate maximum sendable amount before fees
let maxAmountsText = 'Maximum Sendable Amounts: ';
for (const [assetJSON, balance] of Object.entries(walletBalanceResponse['total_amounts'])) {
const asset = JSON.parse(assetJSON);
const maxSendableAmountBeforeFees = balance / totalFeeFactor;
maxAmountsText += `${asset.name}: ${maxSendableAmountBeforeFees.toFixed(2)} `;
}

return {
maxAmountsText: maxAmountsText.trim(),
currentFeesText: `Current Fees - Miner Fee: ${minerFeePercent * 100}%, Reserve Fee: ${reserveFeePercent * 100}%`
};
} catch (error) {
console.error('Error updating max sendable amounts:', error);
return { error: error.message };
}
};

export const fetchTransactionFees = async () => {
try {
const feesResponse = await fetch(`${BASE_URL}/transactions/fees`);
const feeQueryResult = await feesResponse.json();

return {
success: true,
feeStructure: feeQueryResult.fee_structure,
};
} catch (error) {
console.error('Error fetching transaction fees:', error);
return {
success: false,
error: error.message, // Providing the error message for better error handling
};
}
};

export const fetchExchangeData = async () => {
try {
const exchangeResponse = await fetch(`${BASE_URL}/transactions/exchange`);
const exchangeQueryResult = await exchangeResponse.json();

return {
success: true,
exchangeAddress: exchangeQueryResult.address,
};
} catch (error) {
console.error('Error fetching exchange info:', error);
return {
success: false,
error: error.message, // Providing the error message for better error handling
};
}
};

export const submitTransaction = async (endpoint, dataPackage) => {
try {
const response = await fetch(endpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(dataPackage),
});

const responseData = await response.json();
if (response.ok && responseData.message !== 'fail') {
// Transaction was successful
alert('Transaction successful');
return { success: true };
} else {
// Transaction failed
alert('Transaction failed');
return { success: false, message: responseData.message || 'Unknown error' };
}
} catch (error) {
console.error(error);
alert('Transaction failed');
return { success: false, message: error.message || 'Unknown error' };
}
};

export const fetchBlockchainDataFromAPI = async () => {
try {
const response = await fetch(`${BASE_URL}/blockchainData`);
const data = await response.json();
return {
success: true,
data: data.blockchain || []
};
} catch (error) {
console.error('Error fetching blockchain data:', error);
return {
success: false,
error: error.message
};
}
};
22 changes: 10 additions & 12 deletions src/components/ExchangeRatioChart.js
Original file line number Diff line number Diff line change
@@ -1,26 +1,24 @@
import React, { useEffect, useState, useRef } from "react";
import "./ExchangeRatioChart.css";
import { Chart } from 'chart.js/auto';
import { fetchBlockchainDataFromAPI } from "../api/api";

const ExchangeRatioChart = () => {
const [blockchainData, setBlockchainData] = useState([]);
const chartRef = useRef(null);
const [chartInstance, setChartInstance] = useState(null);

const fetchBlockchainData = async () => {
try {
const response = await fetch('/blockchainData');
const data = await response.json();
setBlockchainData(data.blockchain || []);
} catch (error) {
console.error('Error fetching blockchain data:', error);
}
};

useEffect(() => {
const intervalId = setInterval(fetchBlockchainData, 15000);
const fetchData = async () => {
const result = await fetchBlockchainDataFromAPI();
if (result.success) {
setBlockchainData(result.data);
}
};

fetchData();
const intervalId = setInterval(fetchData, 15000);

// Cleanup function to clear the interval
return () => clearInterval(intervalId);
}, []);

Expand Down
14 changes: 6 additions & 8 deletions src/components/ExchangeRatioController.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,19 @@
import React from 'react';
import { useRecoilState } from 'recoil';
import { exchangeRatioState } from '../state/ExchangeRatioState'; // Adjust the path as necessary
import { changeExchangeRatioApi } from '../api/api';

const ExchangeRatioController = () => {
const [exchangeRatio, setExchangeRatio] = useRecoilState(exchangeRatioState);

const changeExchangeRatio = async (newRatio) => {
try {
const response = await fetch(`/changeExchangeRatio?percentage=${newRatio}`, {
method: 'POST',
});
const data = await response.json();
console.info(`Exchange ratio changed to ${newRatio}%`, data);
const result = await changeExchangeRatioApi(newRatio);
if (result.success) {
console.info(`Exchange ratio changed to ${newRatio}%`, result.data);
alert(`Exchange ratio changed to ${newRatio}%`);
setExchangeRatio(newRatio);
} catch (error) {
console.error('Error changing exchange ratio:', error);
} else {
console.error('Error changing exchange ratio:', result.error);
}
};

Expand Down
Loading

0 comments on commit 4c0449b

Please sign in to comment.