Skip to content

Commit

Permalink
check balance before start offramp
Browse files Browse the repository at this point in the history
  • Loading branch information
gianfra-t committed Apr 22, 2024
1 parent 1932e28 commit 2f2ca8a
Show file tree
Hide file tree
Showing 6 changed files with 96 additions and 20 deletions.
54 changes: 54 additions & 0 deletions src/components/InputKeys/BalanceState.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { useEffect, useState } from 'react';
import { ApiPromise } from '@polkadot/api';
import { nativeToDecimal } from '../../helpers/parseNumbers';
import { getApiManagerInstance } from '../../services/polkadot/polkadotApi';
import { ASSET_CODE } from '../../constants/constants';
import {ASSET_ISSUER_RAW} from '../../services/polkadot/index'

export interface UseAccountBalanceResponse {
balance?: string;
isBalanceLoading: boolean;
balanceError?: Error;
}


export const useAccountBalance = (address?: string): UseAccountBalanceResponse => {
const [balance, setBalance] = useState<string>();
const [isBalanceLoading, setIsLoading] = useState(false);
const [balanceError, setError] = useState<Error>();

useEffect(() => {
const fetchBalance = async () => {
const apiManager = await getApiManagerInstance()
const api = await apiManager.getApi();
if (!api || !address) {
setBalance(undefined);
return;
}

try {
setIsLoading(true);
console.log(address)
const response = (await api.api.query.tokens.accounts(address, { Stellar: { AlphaNum4: { code: ASSET_CODE, issuer: ASSET_ISSUER_RAW }} }
)).toHuman();
console.log(response)
const balance = response?.free?.toString() || '0';
const formattedBalance = nativeToDecimal(balance).toString();

setBalance(formattedBalance);
setIsLoading(false);
} catch (err) {
setError(err as Error);
setIsLoading(false);
}
};

fetchBalance();
}, [address]);

return {
balance,
isBalanceLoading,
balanceError,
};
};
30 changes: 25 additions & 5 deletions src/components/InputKeys/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,11 @@ import euroSvg from '../../assets/coins/euro.svg';
import arrowSvg from '../../assets/coins/arrow.svg';
import OpenWallet from '../Wallet';
import { useGlobalState } from '../../GlobalStateProvider';
import {getInstance, ApiManager} from '../../services/polkadot/polkadotApi';
import {getApiManagerInstance, ApiManager} from '../../services/polkadot/polkadotApi';
import { useAccountBalance } from './BalanceState'
import {MIN_WITHDRAWAL_AMOUNT} from '../../constants/constants';
import {nativeToDecimal} from '../../helpers/parseNumbers';

export interface IInputBoxData {
stellarFundingSecret: string;
pendulumSecret: string;
Expand All @@ -25,11 +29,12 @@ const InputBox: React.FC<InputBoxProps> = ({ onSubmit, dAppName }) => {
const [apiManager, setApiManager] = useState<ApiManager>();
const [ss58Format, setSs58Format] = useState<number>(42);


const { balance, isBalanceLoading, balanceError } = useAccountBalance(walletAccount?.address);


useEffect(() => {
const initializeApiManager = async () => {
const manager = await getInstance();
const manager = await getApiManagerInstance();
const { api, ss58Format } = await manager.getApi();
setApiManager(manager);
setSs58Format(ss58Format);
Expand All @@ -44,6 +49,13 @@ const InputBox: React.FC<InputBoxProps> = ({ onSubmit, dAppName }) => {
return;
}

if (balance){
if (Number(balance) < nativeToDecimal(MIN_WITHDRAWAL_AMOUNT).toNumber()){
alert("Insufficient balance to offramp. Minimum withdrawal amount is 10 EURC.");
return;
}
}

const stellarResult = await checkStellarAccount(stellarFundingSecret);
if (stellarResult) {
setIsSubmitted(true);
Expand Down Expand Up @@ -83,8 +95,16 @@ const InputBox: React.FC<InputBoxProps> = ({ onSubmit, dAppName }) => {
{stellarError && <div style={{ color: 'red' }}>{stellarError}</div>}
<div>
<OpenWallet dAppName={dAppName} ss58Format={ss58Format} offrampStarted={isSubmitted} />
</div>

</div>
<div>
{ !walletAccount?.address ? (
null
) : balanceError ? (
<p>Error loading balance</p>
) : (
<p>EURC Balance: {balance}</p>
)}
</div>
{!isSubmitted ? <button onClick={handleSubmit}>Begin Offramp</button> : <div>Offramp Started</div>}
</div>
</div>
Expand Down
8 changes: 5 additions & 3 deletions src/constants/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@ export const TOML_FILE_URL = 'https://mykobo.co/.well-known/stellar.toml';
export const ASSET_CODE = 'EURC';
export const ASSET_ISSUER = 'GAQRF3UGHBT6JYQZ7YSUYCIYWAF4T2SAA5237Q5LIQYJOHHFAWDXZ7NM';
export const EURC_VAULT_ACCOUNT_ID = '6bsD97dS8ZyomMmp1DLCnCtx25oABtf19dypQKdZe6FBQXSm';
//export const HORIZON_URL = 'https://horizon.stellar.org';
export const HORIZON_URL = "https://horizon-testnet.stellar.org";
export const MIN_WITHDRAWAL_AMOUNT = '10000000000000';
export const HORIZON_URL = 'https://horizon.stellar.org';
//export const HORIZON_URL = "https://horizon-testnet.stellar.org";
export const BASE_FEE = '1000000';
export const PENDULUM_WSS = 'ws://localhost:8000';
export const PENDULUM_WSS = 'wss://rpc-pendulum.prd.pendulumchain.tech';
//export const PENDULUM_WSS = 'ws://localhost:8000';

export const ASSET_CODE_MOCK = 'USDC';
export const ASSET_ISSUER_MOCK = 'GAKNDFRRWA3RPWNLTI3G4EBSD3RGNZZOY5WKWYMQ6CQTG3KIEKPYWAYC';
10 changes: 5 additions & 5 deletions src/services/anchor/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -156,11 +156,11 @@ export async function sep24Second(

// TODOmock, testing
// await new Promise((resolve) => setTimeout(resolve, 1000));
return {
amount: "10.3",
memo: "todo",
offrampingAccount: "GADBL6LKYBPNGXBKNONXTFVIRMQIXHH2ZW67SVA2R7XM6VBXMD2O6DIS",
};
// return {
// amount: "10.3",
// memo: "todo",
// offrampingAccount: "GADBL6LKYBPNGXBKNONXTFVIRMQIXHH2ZW67SVA2R7XM6VBXMD2O6DIS",
// };

// end mock testing

Expand Down
4 changes: 2 additions & 2 deletions src/services/polkadot/polkadotApi.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ class ApiManager {
});
const mutex = new Mutex();

const chainProperties = await api.registry.getChainProperties();
const chainProperties = api.registry.getChainProperties();
const ss58Format = Number(chainProperties?.get('ss58Format').toString() || 42);

return { api, mutex, ss58Format };
Expand Down Expand Up @@ -70,7 +70,7 @@ class Mutex {

let instance: ApiManager | undefined = undefined;

export async function getInstance(): Promise<ApiManager> {
export async function getApiManagerInstance(): Promise<ApiManager> {
if (!instance) {
instance = new ApiManager();
await instance.populateApi();
Expand Down
10 changes: 5 additions & 5 deletions src/services/stellar/index.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { Horizon, Keypair, TransactionBuilder, Operation, Networks, Asset, Memo, Transaction, Account } from 'stellar-sdk';
import { HORIZON_URL, BASE_FEE, ASSET_CODE_MOCK, ASSET_ISSUER_MOCK } from '../../constants/constants';
import { HORIZON_URL, BASE_FEE, ASSET_CODE, ASSET_ISSUER } from '../../constants/constants';
import { ISep24Result } from '../anchor';

const horizonServer = new Horizon.Server(HORIZON_URL);
const NETWORK_PASSPHRASE = Networks.TESTNET;
const NETWORK_PASSPHRASE = Networks.PUBLIC;
import { EventStatus } from '../../components/GenericEvent';

export interface IStellarOperations {
Expand Down Expand Up @@ -90,7 +90,7 @@ async function setupStellarAccount(
})
.addOperation(
Operation.changeTrust({
asset: new Asset(ASSET_CODE_MOCK, ASSET_ISSUER_MOCK),
asset: new Asset(ASSET_CODE, ASSET_ISSUER),
}),
)
.setTimeout(30)
Expand Down Expand Up @@ -125,7 +125,7 @@ async function createOfframpTransaction(sep24Result: ISep24Result, ephemeralKeys
.addOperation(
Operation.payment({
amount,
asset: new Asset(ASSET_CODE_MOCK, ASSET_ISSUER_MOCK),
asset: new Asset(ASSET_CODE, ASSET_ISSUER),
destination: offrampingAccount,
}),
)
Expand All @@ -146,7 +146,7 @@ async function createAccountMergeTransaction(fundingSecret: string, ephemeralKey
})
.addOperation(
Operation.changeTrust({
asset: new Asset(ASSET_CODE_MOCK, ASSET_ISSUER_MOCK),
asset: new Asset(ASSET_CODE, ASSET_ISSUER),
limit: '0',
}),
)
Expand Down

0 comments on commit 2f2ca8a

Please sign in to comment.