Skip to content

Commit

Permalink
Battery fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
voloshinskii committed Jan 16, 2024
1 parent 169bcd7 commit f87b190
Show file tree
Hide file tree
Showing 5 changed files with 63 additions and 33 deletions.
60 changes: 39 additions & 21 deletions packages/@core-js/src/managers/BatteryManager.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,42 @@
import { WalletContext, WalletIdentity } from '../Wallet';
import { MessageConsequences } from '../TonAPI';
import { Storage } from '../declarations/Storage';
import { State } from '../utils/State';

export class BatteryManager {
constructor(private ctx: WalletContext, private identity: WalletIdentity) {}
export interface BatteryState {
isLoading: boolean;
balance?: string;
}

public get cacheKey() {
return ['battery', this.ctx.address.ton.raw];
export const batteryState = new State<BatteryState>({
isLoading: false,
balance: undefined,
});

export class BatteryManager {
public state = batteryState;

constructor(
private ctx: WalletContext,
private identity: WalletIdentity,
private storage: Storage,
) {
this.state.persist({
partialize: ({ balance }) => ({ balance }),
storage: this.storage,
key: 'battery',
});
}

public async getBalance() {
public async fetchBalance() {
try {
this.state.set({ isLoading: true });
const data = await this.ctx.batteryapi.getBalance({
headers: {
'X-TonConnect-Auth': this.identity.tonProof,
},
});
return data.balance;
} catch (err) {
return null;
}
}

public async refetchBalance() {
try {
await this.ctx.queryClient.refetchQueries({
refetchPage: (_, index) => index === 0,
queryKey: this.cacheKey,
});
this.state.set({ isLoading: false, balance: data.balance });
} catch (err) {
return null;
}
Expand Down Expand Up @@ -58,7 +68,7 @@ export class BatteryManager {
);

if (data.success) {
this.refetchBalance();
this.fetchBalance();
}

return data;
Expand All @@ -78,7 +88,7 @@ export class BatteryManager {
},
);

await this.refetchBalance();
await this.fetchBalance();

return data.transactions;
} catch (err) {
Expand All @@ -97,7 +107,7 @@ export class BatteryManager {
},
);

await this.refetchBalance();
await this.fetchBalance();

return data.purchases;
} catch (err) {
Expand All @@ -117,7 +127,7 @@ export class BatteryManager {
},
);

await this.refetchBalance();
await this.fetchBalance();
} catch (err) {
console.log('[battery sendMessage]', err);
throw new Error(err);
Expand All @@ -139,4 +149,12 @@ export class BatteryManager {
throw new Error(err);
}
}

public async rehydrate() {
return this.state.rehydrate();
}

public async clear() {
return this.state.clear();
}
}
3 changes: 2 additions & 1 deletion packages/mobile/src/blockchain/wallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { getServerConfig } from '$shared/constants';
import { UnlockedVault, Vault } from './vault';
import {
Address as AddressFormatter,
BASE_FORWARD_AMOUNT,
ContractService,
contractVersionsMap,
isActiveAccount,
Expand Down Expand Up @@ -498,7 +499,7 @@ export class TonWallet {
throw new Error(t('send_fee_estimation_error'));
}

const transferAmount = feeNano.plus(toNano('0.05').toString());
const transferAmount = feeNano.plus(BASE_FORWARD_AMOUNT.toString()).toString();

if (this.isLockup()) {
const lockupBalances = await this.getLockupBalances(sender);
Expand Down
12 changes: 7 additions & 5 deletions packages/mobile/src/core/NFTSend/NFTSend.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ export const NFTSend: FC<Props> = (props) => {

const excessesAccount = !config.get('disable_battery_send')
? await tk.wallet.battery.getExcessesAccount()
: null;
: undefined;

const nftTransferMessages = [
internal({
Expand All @@ -133,9 +133,10 @@ export const NFTSend: FC<Props> = (props) => {
secretKey: Buffer.alloc(64),
});

const response = await emulateWithBattery(boc, {
params: [setBalanceForEmulation(toNano('2'))], // Emulate with higher balance to calculate fair amount to send
});
const response = await emulateWithBattery(
boc,
[setBalanceForEmulation(toNano('2'))], // Emulate with higher balance to calculate fair amount to send
);

setConsequences(response.emulateResult);
setIsBattery(response.battery);
Expand Down Expand Up @@ -175,7 +176,7 @@ export const NFTSend: FC<Props> = (props) => {
: BigInt(Math.abs(consequences?.event.extra!)) + BASE_FORWARD_AMOUNT;

const checkResult = await checkIsInsufficient(totalAmount.toString());
if (checkResult.insufficient) {
if (!isBattery && checkResult.insufficient) {
openInsufficientFundsModal({
totalAmount: totalAmount.toString(),
balance: checkResult.balance,
Expand Down Expand Up @@ -220,6 +221,7 @@ export const NFTSend: FC<Props> = (props) => {
}, [
comment,
consequences?.event.extra,
isBattery,
nftAddress,
recipient,
total.isRefund,
Expand Down
8 changes: 4 additions & 4 deletions packages/mobile/src/store/wallet/sagas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ import { clearSubscribeStatus } from '$utils/messaging';
import { useRatesStore } from '$store/zustand/rates';
import { Cell } from '@ton/core';
import nacl from 'tweetnacl';
import { encryptMessageComment } from '@tonkeeper/core';
import { BASE_FORWARD_AMOUNT, encryptMessageComment } from '@tonkeeper/core';
import { goBack } from '$navigation/imperative';
import { trackEvent } from '$utils/stats';
import { tk } from '@tonkeeper/shared/tonkeeper';
Expand Down Expand Up @@ -448,10 +448,10 @@ function* confirmSendCoinsWorker(action: ConfirmSendCoinsAction) {
yield delay(100);

if (onNext) {
if (!isSendAll && onInsufficientFunds) {
if ((tokenType !== TokenType.TON || !isSendAll) && onInsufficientFunds) {
const amountNano =
tokenType === TokenType.Jetton
? new BigNumber(toNano(fee)).plus(toNano('0.05')).toString()
? new BigNumber(toNano(fee)).plus(BASE_FORWARD_AMOUNT.toString()).toString()
: new BigNumber(toNano(fee)).plus(toNano(amount)).toString();
const address = yield call([wallet.ton, 'getAddress']);
const { balance } = yield call(Tonapi.getWalletInfo, address);
Expand Down Expand Up @@ -541,7 +541,7 @@ function* sendCoinsWorker(action: SendCoinsAction) {
unlockedVault,
commentValue,
sendWithBattery,
BigNumber(toNano(fee)).plus(toNano('0.05')).toString(),
BigNumber(toNano(fee)).plus(BASE_FORWARD_AMOUNT.toString()).toString(),
);
} else if (tokenType === TokenType.TON && currency === CryptoCurrencies.Ton) {
yield call(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
import { memo, useCallback, useState } from 'react';
import { Button, Input, Modal, Spacer, Steezy, Toast, View } from '@tonkeeper/uikit';
import {
Button,
Input,
isIOS,
Modal,
Spacer,
Steezy,
Toast,
View,
} from '@tonkeeper/uikit';
import { navigation, SheetActions, useNavigation } from '@tonkeeper/router';
import { t } from '@tonkeeper/shared/i18n';
import { tk } from '../../tonkeeper';
Expand Down Expand Up @@ -36,10 +45,10 @@ export const RechargeByPromoModal = memo(() => {
withClearButton
value={code}
onChangeText={onChangeText}
placeholder={t('battery.promocode.placeholder')}
/>
<Spacer y={32} />
<Button onPress={applyPromo} title={t('battery.promocode.apply')} />
<Spacer y={16} />
</View>
<Modal.Footer />
</Modal.Content>
Expand Down

0 comments on commit f87b190

Please sign in to comment.