Skip to content

Commit

Permalink
Make resync not delete offers by default
Browse files Browse the repository at this point in the history
  • Loading branch information
Rigidity committed Nov 28, 2024
1 parent ccc6c80 commit 6492390
Show file tree
Hide file tree
Showing 5 changed files with 86 additions and 32 deletions.
2 changes: 2 additions & 0 deletions crates/sage-api/src/requests/keys.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ pub struct LogoutResponse {}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, Type)]
pub struct Resync {
pub fingerprint: u32,
#[serde(default)]
pub delete_offer_files: bool,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, Type)]
Expand Down
21 changes: 20 additions & 1 deletion crates/sage/src/endpoints/keys.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,26 @@ impl Sage {
self.switch_wallet().await?;
}

self.delete_wallet_db(req.fingerprint)?;
let pool = self.connect_to_database(req.fingerprint).await?;

sqlx::query!(
"
DELETE FROM `coin_states`;
DELETE FROM `transactions`;
DELETE FROM `peaks`;
DELETE FROM `cats`;
DELETE FROM `future_did_names`;
DELETE FROM `collections`;
DELETE FROM `nft_data`;
DELETE FROM `nft_uris`;
"
)
.execute(&pool)
.await?;

if req.delete_offer_files {
sqlx::query!("DELETE FROM `offers`").execute(&pool).await?;
}

if login {
self.config.app.active_fingerprint = Some(req.fingerprint);
Expand Down
32 changes: 17 additions & 15 deletions crates/sage/src/sage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ use sage_keychain::Keychain;
use sage_wallet::{PeerState, SyncCommand, SyncEvent, SyncManager, SyncOptions, Timeouts, Wallet};
use sqlx::{
sqlite::{SqliteConnectOptions, SqliteJournalMode, SqlitePoolOptions},
ConnectOptions,
ConnectOptions, SqlitePool,
};
use tokio::sync::{mpsc, Mutex};
use tracing::{error, info, Level};
Expand Down Expand Up @@ -231,19 +231,10 @@ impl Sage {
};

let intermediate_pk = master_to_wallet_unhardened_intermediate(&master_pk);
let path = self.wallet_db_path(fingerprint)?;

let pool = SqlitePoolOptions::new()
.connect_with(
SqliteConnectOptions::from_str(&format!("sqlite://{}?mode=rwc", path.display()))?
.journal_mode(SqliteJournalMode::Wal)
.log_statements(log::LevelFilter::Trace),
)
.await?;

sqlx::migrate!("../../migrations").run(&pool).await?;

let pool = self.connect_to_database(fingerprint).await?;
let db = Database::new(pool);

let wallet = Arc::new(Wallet::new(
db.clone(),
fingerprint,
Expand Down Expand Up @@ -363,12 +354,23 @@ impl Sage {
Ok(amount)
}

pub fn delete_wallet_db(&self, fingerprint: u32) -> Result<()> {
pub async fn connect_to_database(&self, fingerprint: u32) -> Result<SqlitePool> {
let path = self.wallet_db_path(fingerprint)?;
Ok(fs::remove_file(path)?)

let pool = SqlitePoolOptions::new()
.connect_with(
SqliteConnectOptions::from_str(&format!("sqlite://{}?mode=rwc", path.display()))?
.journal_mode(SqliteJournalMode::Wal)
.log_statements(log::LevelFilter::Trace),
)
.await?;

sqlx::migrate!("../../migrations").run(&pool).await?;

Ok(pool)
}

pub fn wallet_db_path(&self, fingerprint: u32) -> Result<PathBuf> {
fn wallet_db_path(&self, fingerprint: u32) -> Result<PathBuf> {
let path = self.path.join("wallets").join(fingerprint.to_string());
fs::create_dir_all(&path)?;
let network_id = &self.config.network.network_id;
Expand Down
2 changes: 1 addition & 1 deletion src/bindings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -618,7 +618,7 @@ export type RemovePeer = { ip: string; ban: boolean }
export type RemovePeerResponse = Record<string, never>
export type RenameKey = { fingerprint: number; name: string }
export type RenameKeyResponse = Record<string, never>
export type Resync = { fingerprint: number }
export type Resync = { fingerprint: number; delete_offer_files?: boolean }
export type ResyncResponse = Record<string, never>
export type SecretKeyInfo = { mnemonic: string | null; secret_key: string }
export type SendCat = { asset_id: string; address: string; amount: Amount; fee: Amount; auto_submit?: boolean }
Expand Down
61 changes: 46 additions & 15 deletions src/pages/Login.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,11 @@ import { useNavigate } from 'react-router-dom';
import { commands, KeyInfo, SecretKeyInfo } from '../bindings';
import Container from '../components/Container';
import { loginAndUpdateState } from '../state';
import { Switch } from '@/components/ui/switch';

export default function Login() {
const [keys, setKeys] = useState<KeyInfo[] | null>(null);
const [network, setNetwork] = useState<string | null>(null);

const navigate = useNavigate();

Expand All @@ -45,6 +47,12 @@ export default function Login() {
setKeys(res.data.keys);
}
});

commands.networkConfig().then((res) => {
if (res.status === 'ok') {
setNetwork(res.data.network_id);
}
});
}, []);

useEffect(() => {
Expand All @@ -68,12 +76,18 @@ export default function Login() {
</div>
</>
)}
</div>{' '}
</div>
{keys !== null ? (
keys.length ? (
<div className='grid md:grid-cols-2 lg:grid-cols-3 gap-4'>
{keys.map((key, i) => (
<WalletItem key={i} info={key} keys={keys} setKeys={setKeys} />
<WalletItem
key={i}
network={network}
info={key}
keys={keys}
setKeys={setKeys}
/>
))}
</div>
) : (
Expand All @@ -99,30 +113,39 @@ function SkeletonWalletList() {
}

interface WalletItemProps {
network: string | null;
info: KeyInfo;
keys: KeyInfo[];
setKeys: (keys: KeyInfo[]) => void;
}

function WalletItem({ info, keys, setKeys }: WalletItemProps) {
function WalletItem({ network, info, keys, setKeys }: WalletItemProps) {
const navigate = useNavigate();

const [anchorEl, setAnchorEl] = useState<HTMLElement | null>(null);
const [anchorEl, _setAnchorEl] = useState<HTMLElement | null>(null);
const isMenuOpen = Boolean(anchorEl);

const [isDeleteOpen, setDeleteOpen] = useState(false);
const [isRenameOpen, setRenameOpen] = useState(false);

const [isDetailsOpen, setDetailsOpen] = useState(false);
const [isResyncOpen, setResyncOpen] = useState(false);
const [secrets, setSecrets] = useState<SecretKeyInfo | null>(null);

const [isRenameOpen, setRenameOpen] = useState(false);
const [newName, setNewName] = useState('');

const [secrets, setSecrets] = useState<SecretKeyInfo | null>(null);
const [isResyncOpen, setResyncOpen] = useState(false);
const [deleteOffers, setDeleteOffers] = useState(false);

const resyncSelf = () => {
commands.resync({ fingerprint: info.fingerprint }).then((res) => {
if (res.status === 'error') return;
setResyncOpen(false);
});
commands
.resync({
fingerprint: info.fingerprint,
delete_offer_files: deleteOffers,
})
.then((res) => {
if (res.status === 'error') return;
setResyncOpen(false);
});
};

const deleteSelf = () => {
Expand Down Expand Up @@ -224,7 +247,7 @@ function WalletItem({ info, keys, setKeys }: WalletItemProps) {
}}
>
<EraserIcon className='mr-2 h-4 w-4' />
<span>Resync</span>
<span>Resync ({network})</span>
</DropdownMenuItem>
<DropdownMenuItem
className='cursor-pointer text-red-600 focus:text-red-500'
Expand Down Expand Up @@ -264,11 +287,19 @@ function WalletItem({ info, keys, setKeys }: WalletItemProps) {
>
<DialogContent>
<DialogHeader>
<DialogTitle>Resync Wallet</DialogTitle>
<DialogTitle>Resync on {network}</DialogTitle>
<DialogDescription>
Are you sure you want to resync this wallet's data? This will
remove custom names for tokens and profiles and redownload all of
the data from the network.
redownload data from the network which can take a while depending
on the size of the wallet.
<div className='flex items-center gap-2 my-2'>
<label htmlFor='deleteOffers'>Delete saved offer files</label>
<Switch
id='deleteOffers'
checked={deleteOffers}
onCheckedChange={(value) => setDeleteOffers(value)}
/>
</div>
</DialogDescription>
</DialogHeader>
<DialogFooter>
Expand Down

0 comments on commit 6492390

Please sign in to comment.