Compare commits

...
6 Commits
10 changed files with 259 additions and 83 deletions
+5
View File
@@ -0,0 +1,5 @@
# Development environment variables
# These are automatically loaded when running 'npm start'
REACT_APP_DEX_SERVER=http://localhost:5700
#REACT_APP_NOSTR_REST_API_URL=http://localhost:5942
+5
View File
@@ -0,0 +1,5 @@
# Production environment variables
# These are automatically loaded when running 'npm run build'
REACT_APP_DEX_SERVER=https://dex-api.fullstack.cash
REACT_APP_NOSTR_REST_API_URL=https://nostr-relay-api.psfoundation.info
@@ -7,33 +7,175 @@
// Global npm libraries
import React, { useState } from 'react'
import { Button, Modal, Container } from 'react-bootstrap'
import { Button, Modal, Container, Row, Col, Spinner } from 'react-bootstrap'
import Sweeper from 'bch-token-sweep'
function CancelCounterOfferBtn (props) {
const [show, setShow] = useState(false)
const [statusMsg, setStatusMsg] = useState('')
const [hideSpinner, setHideSpinner] = useState(false)
const [isProcessing, setIsProcessing] = useState(false)
const [showConfirmation, setShowConfirmation] = useState(true) // show the confirmation view
// Update wallet state function
const updateWalletState = async () => {
const wallet = props.appData.wallet
const bchBalance = await wallet.getBalance({ bchAddress: wallet.walletInfo.cashAddress })
await wallet.initialize()
const slpTokens = await wallet.listTokens(wallet.walletInfo.cashAddress)
props.appData.updateBchWalletState({ walletObj: { bchBalance, slpTokens }, appData: props.appData })
}
// Handle cancel/sweep function
const handleCancel = async () => {
try {
console.log('Canceling Counter Offer')
// Hide confirmation and show processing
setShowConfirmation(false)
setHideSpinner(false)
setStatusMsg('')
setIsProcessing(true)
// Get the keypair that holds Counter Offer UTXOs.
// This uses the same derivation path as used in the counter offers page (index 1)
const bchDexLib = props.appData.dexLib
const keyPair = await bchDexLib.take.util.getKeyPair(1)
const wif = keyPair.wif
// Get wallet info for sweeping
const walletWif = props.appData.wallet.walletInfo.privateKey
const toAddr = props.appData.wallet.slpAddress
// Instance the Sweep library and populate UTXOs from network
const sweep = new Sweeper(wif, walletWif, props.appData.wallet)
await sweep.populateObjectFromNetwork()
// Constructing the sweep transaction
const hex = await sweep.sweepTo(toAddr)
const txid = await props.appData.wallet.ar.sendTx(hex)
// Generate success status message
const newStatusMsg = (
<>
<p>Sweep succeeded!</p>
<p>Counter Offer has been canceled.</p>
<p>Transaction ID: {txid}</p>
<p>
<a href={`https://blockchair.com/bitcoin-cash/transaction/${txid}`} target='_blank' rel='noreferrer'>
TX on Blockchair BCH Block Explorer
</a>
</p>
<p>
<a href={`https://token.fullstack.cash/transactions/?txid=${txid}`} target='_blank' rel='noreferrer'>
TX on token explorer
</a>
</p>
</>
)
setHideSpinner(true)
setStatusMsg(newStatusMsg)
setIsProcessing(false)
// Update wallet state to reflect the changes
await updateWalletState()
// Refresh the counter offers list if refreshTokens function is provided
if (props.refreshTokens) {
// Small delay to ensure blockchain state is updated
setTimeout(() => {
props.refreshTokens()
}, 2000)
}
} catch (err) {
console.error('Error in handleCancel(): ', err)
setHideSpinner(true)
setIsProcessing(false)
setStatusMsg(<b style={{ color: 'red' }}>{`Error: ${err.message}`}</b>)
}
}
const handleClose = () => {
// Deny close if the cancel is in progress.
if (isProcessing) {
return
}
setShow(false)
// props.instance.setState({ showModal: false })
setStatusMsg('')
setHideSpinner(false)
setIsProcessing(false)
setShowConfirmation(true) // Reset confirmation state for next time
}
const handleOpen = () => {
setShow(true)
// Don't start the cancel process immediately - wait for user confirmation
}
return (
<>
<Button variant='danger' onClick={handleOpen} disabled>Cancel</Button>
<Button variant='danger' onClick={handleOpen} disabled={isProcessing}>Cancel</Button>
<Modal show={show} onHide={handleClose}>
<Modal.Header closeButton>
<Modal.Title>Cancel </Modal.Title>
<Modal.Title>Cancel Counter Offer</Modal.Title>
</Modal.Header>
<Modal.Body>
<Container>
{/** ... */}
</Container>
{showConfirmation
? (
<Container>
<Row>
<Col style={{ textAlign: 'center' }}>
<p>Are you sure you want to cancel this Counter Offer?</p>
<p style={{ color: '#666', fontSize: '0.9em' }}>
This action will sweep the Counter Offer UTXOs back to your wallet.
</p>
</Col>
</Row>
</Container>
)
: (
<Container>
<Row>
{!hideSpinner && (
<Col style={{ display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
<span style={{ marginRight: '10px' }}>Canceling Counter Offer...</span>
<Spinner animation='border' />
</Col>
)}
</Row>
<br />
{statusMsg && (
<Row>
<Col style={{ textAlign: 'center' }}>{statusMsg}</Col>
</Row>
)}
</Container>
)}
</Modal.Body>
<Modal.Footer />
<Modal.Footer>
{showConfirmation && (
<Row style={{ width: '100%' }}>
<Col xs={12} className='text-center'>
<Button
variant='secondary'
style={{ minWidth: '100px', marginRight: '10px' }}
onClick={handleClose}
>
No, Keep Open
</Button>
<Button
variant='danger'
style={{ minWidth: '100px' }}
onClick={handleCancel}
>
Yes, Cancel It
</Button>
</Col>
</Row>
)}
</Modal.Footer>
</Modal>
</>
)
@@ -12,7 +12,7 @@ import InfoButton from './info-button'
import CancelCounterOfferBtn from './cancel-counter-offer-btn'
function CounterOfferCard (props) {
const { token } = props
const { token, appData, refreshTokens } = props
const [icon, setIcon] = useState(token.icon)
// Update icon state every token.icon changes
@@ -71,7 +71,11 @@ function CounterOfferCard (props) {
</Col>
<Col xs={4}>
<CancelCounterOfferBtn token={props.token} />
<CancelCounterOfferBtn
token={props.token}
appData={appData}
refreshTokens={refreshTokens}
/>
</Col>
</Row>
@@ -10,7 +10,6 @@ import AsyncLoad from '../../../services/async-load'
function BuyButton (props) {
const { token, appData, onSuccess } = props
console.log('props: ', props)
const [show, setShow] = useState(false) // show the modal
const [onFetch, setOnFetch] = useState(false) // show the spinner
const [error, setError] = useState(false) // show the error message
+37 -12
View File
@@ -74,7 +74,8 @@ function NftsForSale (props) {
return offer
}
}, [appData])
// Function to process token metadata (iconUrl , userData).
// Function to process token metadata (iconUrl , userData , tokenData).
const processOfferMetadata = useCallback(async (offer) => {
try {
// Token icon
@@ -82,7 +83,15 @@ function NftsForSale (props) {
offer.icon = offer.tokenIconUrl
offer.iconAlreadyDownloaded = true
offer.userData = JSON.parse(offer.userDataStr)
offer.mutableFromBackend = true
offer.mutableDataSource = 'backend'
}
// tokenData
if (offer.tokenData) {
offer.tokenDataFromBackend = true
offer.tokenDataSource = 'backend'
}
return offer
} catch (error) {
return offer
@@ -126,8 +135,10 @@ function NftsForSale (props) {
for (let i = 0; i < tokens.length; i++) {
const thisToken = tokens[i]
// data does not need to be downloaded, so continue with the next one
if (thisToken.dataAlreadyDownloaded) continue
// Skip if already has tokenData (from backend or cache)
if (thisToken.dataAlreadyDownloaded || thisToken.tokenData) {
continue
}
// Try to get token data.
const tokenData = await appData.wallet.getTokenData(thisToken.tokenId)
@@ -135,6 +146,7 @@ function NftsForSale (props) {
if (tokenData) {
// Set data to the token object , this can be used to display the token name in the token card component.
thisToken.tokenData = tokenData
thisToken.tokenDataSource = 'blockchain'
}
// Mark token to prevent fetch token data again.
@@ -195,6 +207,7 @@ function NftsForSale (props) {
// Set the icon url to the token , this can be used to display the icon in the token card component.
thisToken.icon = iconUrl
thisToken.userData = userData
thisToken.mutableDataSource = 'blockchain'
}
// Mark token to prevent fetch token icon again.
@@ -210,15 +223,23 @@ function NftsForSale (props) {
// Check if token data exists in the cache and add it to the tokens object.
const reviewNftCachedData = useCallback(async (offers) => {
const cacheData = appData.nftForSaleCacheData
console.log(`Token data from cache: ${JSON.stringify(cacheData, null, 2)}`)
// console.log(`Token data from cache: ${JSON.stringify(cacheData, null, 2)}`)
// Map all offers
for (let i = 0; i < offers.length; i++) {
const thisToken = offers[i]
// console.log(`Review offers:`,thisToken)
const cacheToken = cacheData[thisToken.tokenId]
// If cache data exists, add it to the token object
if (cacheToken) {
thisToken.tokenData = cacheToken.tokenData
// Only use cache if backend didn't provide the data
if (cacheToken && !thisToken.icon) {
thisToken.icon = cacheToken.tokenIcon
thisToken.mutableDataSource = 'cache'
}
if (cacheToken && !thisToken.tokenData) {
thisToken.tokenData = cacheToken.tokenData
thisToken.tokenDataSource = 'cache'
}
}
}, [appData])
@@ -228,13 +249,17 @@ function NftsForSale (props) {
// Map all offers
for (let i = 0; i < offers.length; i++) {
const thisToken = offers[i]
// save token icon and token data in cache
const newTokenCacheData = {
tokenIcon: thisToken.icon,
tokenData: thisToken.tokenData
}
console.log('newTokenCacheData: ', newTokenCacheData)
// Only cache if we fetched it ourselves (not from backend)
// Backend data is already "cached" server-side, no need to duplicate
if (thisToken.tokenDataFromBackend && thisToken.mutableFromBackend) continue
const newTokenCacheData = {}
if (!thisToken.tokenDataFromBackend) newTokenCacheData.tokenData = thisToken.tokenData
if (!thisToken.mutableFromBackend) newTokenCacheData.tokenIcon = thisToken.icon
appData.updateNFTCachedData(thisToken.tokenId, newTokenCacheData)
}
}, [appData])
@@ -13,6 +13,7 @@ import BuyButton from './buy-button'
import SellerProfile from './seller-profile'
function TokenCard (props) {
const { token, appData, handleRefresh, hideBuyBtn } = props
console.log('token', token)
const [icon, setIcon] = useState(token.icon)
const [tokenData, setTokenData] = useState(token.tokenData)
@@ -40,6 +40,29 @@ function NFTForSale (props) {
}
}, [appData])
// Function to process token metadata (iconUrl , userData , tokenData).
const processOfferMetadata = useCallback(async (offer) => {
try {
// Token icon
if (offer.tokenIconUrl) {
offer.icon = offer.tokenIconUrl
offer.iconAlreadyDownloaded = true
offer.userData = JSON.parse(offer.userDataStr)
offer.mutableFromBackend = true
offer.mutableDataSource = 'backend'
}
// tokenData
if (offer.tokenData) {
offer.tokenDataFromBackend = true
offer.tokenDataSource = 'backend'
}
return offer
} catch (error) {
return offer
}
}, [])
// Fetch offers
const getNftOffers = useCallback(async (page = 0) => {
try {
@@ -57,7 +80,8 @@ function NFTForSale (props) {
for (let i = 0; i < rawOffers.length; i++) {
const offer = rawOffers[i]
const processedOffer = await processTokenData(offer)
processedOffers.push(processedOffer)
const processedOfferMetadata = await processOfferMetadata(processedOffer)
processedOffers.push(processedOfferMetadata)
}
setOffersAreLoaded(true)
@@ -68,7 +92,7 @@ function NFTForSale (props) {
setOffersAreLoaded(true)
throw err
}
}, [processTokenData, profileAddresses])
}, [processTokenData, processOfferMetadata, profileAddresses])
// This function loads the token data .
const lazyLoadTokenData = useCallback(async (tokens) => {
@@ -78,8 +102,10 @@ function NFTForSale (props) {
for (let i = 0; i < tokens.length; i++) {
const thisToken = tokens[i]
// data does not need to be downloaded, so continue with the next one
if (thisToken.dataAlreadyDownloaded) continue
// Skip if already has tokenData (from backend or cache)
if (thisToken.dataAlreadyDownloaded || thisToken.tokenData) {
continue
}
// Try to get token data.
const tokenData = await appData.wallet.getTokenData(thisToken.tokenId)
@@ -87,6 +113,7 @@ function NFTForSale (props) {
if (tokenData) {
// Set data to the token object , this can be used to display the token name in the token card component.
thisToken.tokenData = tokenData
thisToken.tokenDataSource = 'blockchain'
}
// Mark token to prevent fetch token data again.
@@ -146,6 +173,7 @@ function NFTForSale (props) {
// Set the icon url to the token , this can be used to display the icon in the token card component.
thisToken.icon = iconUrl
thisToken.userData = userData
thisToken.mutableDataSource = 'blockchain'
}
// Mark token to prevent fetch token icon again.
@@ -161,15 +189,23 @@ function NFTForSale (props) {
// Check if token data exists in the cache and add it to the tokens object.
const reviewNftCachedData = useCallback(async (offers) => {
const cacheData = appData.nftForSaleCacheData
console.log(`Token data from cache: ${JSON.stringify(cacheData, null, 2)}`)
// console.log(`Token data from cache: ${JSON.stringify(cacheData, null, 2)}`)
// Map all offers
for (let i = 0; i < offers.length; i++) {
const thisToken = offers[i]
// console.log(`Review offers:`,thisToken)
const cacheToken = cacheData[thisToken.tokenId]
// If cache data exists, add it to the token object
if (cacheToken) {
thisToken.tokenData = cacheToken.tokenData
// Only use cache if backend didn't provide the data
if (cacheToken && !thisToken.icon) {
thisToken.icon = cacheToken.tokenIcon
thisToken.mutableDataSource = 'cache'
}
if (cacheToken && !thisToken.tokenData) {
thisToken.tokenData = cacheToken.tokenData
thisToken.tokenDataSource = 'cache'
}
}
}, [appData])
@@ -179,13 +215,17 @@ function NFTForSale (props) {
// Map all offers
for (let i = 0; i < offers.length; i++) {
const thisToken = offers[i]
// save token icon and token data in cache
const newTokenCacheData = {
tokenIcon: thisToken.icon,
tokenData: thisToken.tokenData
}
console.log('newTokenCacheData: ', newTokenCacheData)
// Only cache if we fetched it ourselves (not from backend)
// Backend data is already "cached" server-side, no need to duplicate
if (thisToken.tokenDataFromBackend && thisToken.mutableFromBackend) continue
const newTokenCacheData = {}
if (!thisToken.tokenDataFromBackend) newTokenCacheData.tokenData = thisToken.tokenData
if (!thisToken.mutableFromBackend) newTokenCacheData.tokenIcon = thisToken.icon
appData.updateNFTCachedData(thisToken.tokenId, newTokenCacheData)
}
}, [appData])
-46
View File
@@ -105,30 +105,6 @@ const SweepWif = (props) => {
}
}
const handleCancelCounterOffers = async () => {
try {
console.log('Executing handleCancelCounterOffers()')
// Set modal initial state
// setShowModal(true)
// setHideSpinner(false)
// setStatusMsg('')
// Get the keypair that holds Counter Offer UTXOs.
const bchDexLib = appData.dexLib
const keyPair = await bchDexLib.take.util.getKeyPair(1)
const wif = keyPair.wif
// console.log(`WIF: ${wif}`)
// Sweep the private key holding the Counter Offer UTXOs.
setWifToSweep(wif)
await handleSweep()
} catch (err) {
console.error('Error in handleCancelCounterOffers(): ', err)
}
}
// Modal component
const getModal = () => (
<Modal show={showModal} size='lg' onHide={() => setShowModal(false)}>
@@ -207,28 +183,6 @@ const SweepWif = (props) => {
</Col>
</Row>
<br />
<br />
<hr />
<Row>
<Col>
<p>
When a Buy order is created, the coins (UTXO) to pay for it are
moved to a secondary address. Clicking the button below will
sweep those funds back into this main wallet. This will also
cancel/invalidate all open Counter Offers that you've created.
</p>
</Col>
</Row>
<Row style={{ textAlign: 'center' }}>
<Col>
<Button onClick={handleCancelCounterOffers}>
Sweep DEX Trading Wallet
</Button>
</Col>
</Row>
</Container>
{showModal && getModal()}
</>
+2 -1
View File
@@ -14,8 +14,9 @@ const config = {
ghRepo: 'https://github.com/Permissionless-Software-Foundation/bch-dex-taker-v2',
radicleUrl: 'https://app.radicle.network/seeds/maple.radicle.garden/rad:git:hnrkd5cjwwb5tzx37hq9uqm5ubon7ee468xcy/remotes/hyyycncbn9qzqmobnhjq9rry6t4mbjiadzjoyhaknzxjcz3cxkpfpc',
dexServer: 'https://dex-api.fullstack.cash',
// dexServer: 'https://dex-api.fullstack.cash',
// dexServer: 'http://localhost:5700',
dexServer: process.env.REACT_APP_DEX_SERVER || 'https://dex-api.fullstack.cash',
nostrTopic: 'bch-dex-test-topic-02',