Skip to content

Commit

Permalink
feat(wallet): Update StarknetKit wallet connection and integration
Browse files Browse the repository at this point in the history
- Refactor wallet services for latest StarknetKit library
- Improve error handling and connection logic
- Update corresponding test suite
  • Loading branch information
davedumto committed Dec 18, 2024
1 parent 4368569 commit a1ef1fe
Show file tree
Hide file tree
Showing 9 changed files with 29,564 additions and 1,645 deletions.
23,899 changes: 23,899 additions & 0 deletions frontend/package-lock.json

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
"react-router-dom": "^6.27.0",
"react-scripts": "^5.0.1",
"react-toastify": "^10.0.6",
"starknetkit": "^2.6.1",
"web-vitals": "^2.1.4",
"zustand": "^5.0.1"
},
Expand Down
15 changes: 7 additions & 8 deletions frontend/src/services/contract.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,28 +5,27 @@ import { axiosInstance } from '../utils/axios';
export async function deployContract(walletId) {
try {
console.log('Connecting to StarkNet wallet...');
// Connect to StarkNet wallet

const starknet = await connect();

// Ensure the wallet connection is successful

if (!starknet || !starknet.isConnected) {
throw new Error('Wallet not connected');
}

console.log('Wallet connected:');

// Prepare the deploy contract transaction object

const deployContractTransaction = getDeployContractData(walletId);
if (!deployContractTransaction) {
throw new Error('Failed to retrieve contract deployment data');
}

// Execute the deployment transaction
console.log('Deploying contract...');
const result = await starknet.account.deployContract(deployContractTransaction);
console.log('Contract deployed successfully:', result);

// Wait for the transaction to be confirmed

await starknet.account.waitForTransaction(result.transaction_hash);
console.log('Transaction confirmed:', result.transaction_hash);

Expand All @@ -44,19 +43,19 @@ export async function checkAndDeployContract(walletId) {
try {
console.log('Checking if contract is deployed for wallet ID:', walletId);

// Check if the contract is deployed by querying the backend

const response = await axiosInstance.get(`/api/check-user?wallet_id=${walletId}`);
console.log('Backend response:', response.data);

// If the contract is not deployed, deploy it

if (!response.data.is_contract_deployed) {
console.log('Contract not deployed. Deploying...');
const result = await deployContract(walletId);
const contractAddress = result.contractAddress;

console.log('Contract address:', contractAddress);

// Update the backend with deployment information

await axiosInstance.post(`/api/update-user-contract`, {
wallet_id: walletId,
contract_address: contractAddress,
Expand Down
6 changes: 3 additions & 3 deletions frontend/src/services/transaction.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ export async function sendTransaction(loopLiquidityData, contractAddress) {
throw error;
}
}
/* eslint-disable-next-line no-unused-vars */

async function waitForTransaction(txHash) {
const starknet = await connect();
let receipt = null;
Expand All @@ -51,7 +51,7 @@ async function waitForTransaction(txHash) {
receipt = await starknet.provider.getTransactionReceipt(txHash);
} catch (error) {
console.log('Waiting for transaction to be accepted...');
await new Promise((resolve) => setTimeout(resolve, 5000)); // Wait for 5 seconds before trying again
await new Promise((resolve) => setTimeout(resolve, 5000));
}
}
console.log('Transaction accepted:', receipt);
Expand Down Expand Up @@ -94,7 +94,7 @@ export const handleTransaction = async (connectedWalletId, formData, setError, s

openPositionResponse == openPositionResponse

// Reset form data

setTokenAmount('');
} catch (err) {
console.error('Failed to create position:', err);
Expand Down
59 changes: 29 additions & 30 deletions frontend/src/services/wallet.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import React from 'react';
import { connect } from 'starknetkit';
import { ETH_ADDRESS, STRK_ADDRESS, USDC_ADDRESS } from '../utils/constants';
import { ReactComponent as ETH } from 'assets/icons/ethereum.svg';
Expand All @@ -7,26 +6,25 @@ import { ReactComponent as STRK } from 'assets/icons/strk.svg';

const CRM_TOKEN_ADDRESS = "0x051c4b1fe3bf6774b87ad0b15ef5d1472759076e42944fff9b9f641ff13e5bbe";

// Check if the connected wallet holds the CRM token
export const checkForCRMToken = async (walletAddress) => {
if (process.env.REACT_APP_IS_DEV === "true") {
console.log("Development mode: Skipping CRM token check.");
return true;
}

try {
const starknet = await connect();
if (!starknet.isConnected) {
const { wallet } = await connect();
if (!wallet) {
throw new Error('Wallet not connected');
}

const response = await starknet.provider.callContract({
const response = await wallet.account.callContract({
contractAddress: CRM_TOKEN_ADDRESS,
entrypoint: 'balanceOf',
calldata: [walletAddress],
});

const balance = BigInt(response.result[0]).toString();
const balance = BigInt(response[0]).toString();

if (Number(balance) > 0) {
return true;
Expand All @@ -36,34 +34,36 @@ export const checkForCRMToken = async (walletAddress) => {
}
} catch (error) {
console.error("Error checking CRM token balance:", error);
throw error; // Ensures test will catch errors as thrown
throw error;
}
};

export const connectWallet = async () => {
try {
console.log('Attempting to connect to wallet...');

const starknet = await connect({
const { wallet } = await connect({
include: ['argentX', 'braavos'],
modalMode: "alwaysAsk",
modalTheme: "light",
modalTheme: "light"
});

if (!starknet) {
console.error('No StarkNet object found');
if (!wallet) {
console.error('No wallet found');
throw new Error('Failed to connect to wallet');
}

await starknet.enable();
// Ensure the wallet is connected
await wallet.enable();

if (starknet.isConnected) {
const address = starknet.selectedAddress;
console.log('Wallet successfully connected. Address:', address);
return address;
} else {
throw new Error('Wallet connection failed');
const address = wallet.selectedAddress || wallet.account.address;

if (!address) {
throw new Error('No wallet address found');
}

console.log('Wallet successfully connected. Address:', address);
return address;
} catch (error) {
console.error('Error connecting wallet:', error.message);
throw error;
Expand All @@ -76,15 +76,15 @@ export function logout() {

export async function getTokenBalances(walletAddress) {
try {
const starknet = await connect();
if (!starknet.isConnected) {
const { wallet } = await connect();
if (!wallet) {
throw new Error('Wallet not connected');
}

const tokenBalances = {
ETH: await getTokenBalance(starknet, walletAddress, ETH_ADDRESS),
USDC: await getTokenBalance(starknet, walletAddress, USDC_ADDRESS),
STRK: await getTokenBalance(starknet, walletAddress, STRK_ADDRESS),
ETH: await getTokenBalance(wallet, walletAddress, ETH_ADDRESS),
USDC: await getTokenBalance(wallet, walletAddress, USDC_ADDRESS),
STRK: await getTokenBalance(wallet, walletAddress, STRK_ADDRESS),
};

return tokenBalances;
Expand All @@ -94,15 +94,16 @@ export async function getTokenBalances(walletAddress) {
}
}

async function getTokenBalance(starknet, walletAddress, tokenAddress) {
async function getTokenBalance(wallet, walletAddress, tokenAddress) {
try {
const response = await starknet.provider.callContract({
const response = await wallet.account.callContract({
contractAddress: tokenAddress,
entrypoint: 'balanceOf',
calldata: [walletAddress],
});

const tokenDecimals = (tokenAddress === USDC_ADDRESS) ? 6 : 18;
const balance = BigInt(response.result[0]).toString();
const balance = BigInt(response[0]).toString();
const readableBalance = (Number(balance) / (10 ** tokenDecimals)).toFixed(4);
console.log(`Balance for token ${tokenAddress}:`, readableBalance);
return readableBalance;
Expand All @@ -112,7 +113,6 @@ async function getTokenBalance(starknet, walletAddress, tokenAddress) {
}
}


export const getBalances = async (walletId, setBalances) => {
if (!walletId) return;
try {
Expand All @@ -134,7 +134,6 @@ export const getBalances = async (walletId, setBalances) => {
title: 'STRK',
balance: data.STRK !== undefined ? data.STRK.toString() : '0.00',
},
// { icon: <DAI />, title: 'DAI', balance: data.DAI !== undefined ? data.DAI.toString() : '0.00' }, dont have DAI in the constants file
];

setBalances(updatedBalances);
Expand All @@ -143,5 +142,5 @@ export const getBalances = async (walletId, setBalances) => {
}
};

// Add this line for environments that don't recognize BigInt
const BigInt = window.BigInt;

const BigInt = window.BigInt;
Loading

0 comments on commit a1ef1fe

Please sign in to comment.