Skip to content

Commit

Permalink
Merge pull request #135 from Cryptorubic/hotfix/bridge-gas-fee
Browse files Browse the repository at this point in the history
Hotfix/bridge gas fee
  • Loading branch information
siandreev authored Mar 25, 2021
2 parents a6edbc1 + 1963790 commit 79e18f9
Show file tree
Hide file tree
Showing 13 changed files with 96 additions and 68 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ export class LoginButtonComponent {
try {
await this.authService.signIn();
} catch (error) {
if (error.code === 4001) {
return;
}
const e = error instanceof RubicError ? error : new RubicError();
const data: any = { title: 'Warinig', descriptionText: e.comment };
this.dialog.open(MessageBoxComponent, {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
<span
class="user-profile__text"
[ngClass]="{ 'user-profile__text_iconless': !($currentBlockchain | async)?.imagePath }"
>{{ $currentAccountAddress | async }}</span>
>{{ ($currentUser | async)?.address }}</span>
</div>
<ul *ngIf="$isMobile | async" class="user-profile__list">
<li class="user-profile__item">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { UserInterface } from 'src/app/core/services/auth/models/user.interface'
import { Web3PrivateService } from 'src/app/core/services/blockchain/web3-private-service/web3-private.service';
import { IBlockchain } from 'src/app/shared/models/blockchain/IBlockchain';
import { HeaderStore } from '../../../../services/header.store';
import { AuthService } from '../../../../../services/auth/auth.service';
@Component({
selector: 'app-user-profile',
templateUrl: './user-profile.component.html',
Expand All @@ -30,14 +31,13 @@ export class UserProfileComponent implements AfterViewInit {

public readonly $currentBlockchain: Observable<IBlockchain>;

public readonly $currentAccountAddress: Observable<string>;

constructor(
private readonly elementRef: ElementRef,
private readonly headerStore: HeaderStore,
private readonly router: Router,
private readonly cdr: ChangeDetectorRef,
private web3PrivateService: Web3PrivateService
private web3PrivateService: Web3PrivateService,
private readonly authService: AuthService
) {
this.$isMobile = this.headerStore.getMobileDisplayStatus();
this.$isUserMenuOpened = this.headerStore.getUserMenuOpeningStatus();
Expand All @@ -49,7 +49,7 @@ export class UserProfileComponent implements AfterViewInit {
}
});
this.$currentBlockchain = this.web3PrivateService.onNetworkChanges;
this.$currentAccountAddress = this.web3PrivateService.onAddressChanges;
this.$currentUser = this.authService.getCurrentUser();
}

public ngAfterViewInit(): void {
Expand Down
2 changes: 1 addition & 1 deletion src/app/core/header/components/header/header.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ export class HeaderComponent {
private readonly headerStore: HeaderStore,
private readonly authService: AuthService
) {
this.authService.fetchUser();
this.authService.loadUser();
this.$currentUser = this.authService.getCurrentUser();
this.pageScrolled = false;
this.$isMobileMenuOpened = this.headerStore.getMobileMenuOpeningStatus();
Expand Down
83 changes: 62 additions & 21 deletions src/app/core/services/auth/auth.service.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,32 @@
import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
import { finalize } from 'rxjs/operators';
import { finalize, map } from 'rxjs/operators';
import { HttpClient } from '@angular/common/http';
import { HeaderStore } from '../../header/services/header.store';
import { Web3PrivateService } from '../blockchain/web3-private-service/web3-private.service';
import { HttpService } from '../http/http.service';
import { UserInterface } from './models/user.interface';
import { URLS } from './models/user.service.api';

interface BackendUser {
isLogout?: boolean;
balance: number;
eos_balance: number;
visibleBalance: string;
contracts: number;
eos_address: string;
id: number;
internal_address: string;
internal_btc_address: string;
is_social: boolean;
lang: string;
memo: string;
use_totp: boolean;
username: string;
is_ghost?: boolean;
is_swaps_admin?: any;
}

/**
* Service that provides methods for working with authentication and user interaction.
*/
Expand All @@ -24,10 +44,15 @@ export class AuthService {
*/
private readonly $currentUser: BehaviorSubject<UserInterface>;

get user(): UserInterface {
return this.$currentUser.getValue();
}

constructor(
private readonly headerStore: HeaderStore,
private readonly httpService: HttpService,
private readonly web3Service: Web3PrivateService
private readonly web3Service: Web3PrivateService,
private readonly httpClient: HttpClient
) {
this.$currentUser = new BehaviorSubject<UserInterface>(undefined);
this.web3Service.onAddressChanges.subscribe(address => {
Expand All @@ -36,8 +61,11 @@ export class AuthService {
}
const user = this.$currentUser.getValue();
// user inited, account not authorized on backend or authorized other account
if (user !== undefined && (user === null || user?.username !== address) && address) {
this.signIn();
if (user !== undefined && (user === null || user?.address !== address) && address) {
/* this.$currentUser.next(null);
this.signIn(); */
window.location.reload();
// TODO: надо продумать модальные окна на кейсы, когда юзер сменил адрес в метамаске но не подписал nonce с бэка
}
});
}
Expand All @@ -53,22 +81,10 @@ export class AuthService {
/**
* @description Fetch user data from backend.
*/
public fetchUser(): void {
if (this.web3Service.isProviderActive) {
this.httpService.get(URLS.PROFILE).subscribe(
(user: UserInterface) => {
this.$currentUser.next(user);
},
() => {
this.$currentUser.next(null);
},
() => {
this.isAuthProcess = false;
}
);
} else {
this.$currentUser.next(null);
}
private fetchUser(): Observable<UserInterface> {
return this.httpService
.get(URLS.PROFILE)
.pipe(map((user: BackendUser) => ({ address: user.username })));
}

/**
Expand All @@ -91,6 +107,28 @@ export class AuthService {
.toPromise();
}

public async loadUser() {
this.isAuthProcess = true;
this.fetchUser().subscribe(
async user => {
await this.web3Service.activate();
if (this.web3Service.address !== user.address) {
this.signOut()
.pipe(
finalize(() => {
this.signIn();
})
)
.subscribe();
} else {
this.$currentUser.next(user);
}
this.isAuthProcess = false;
},
() => this.$currentUser.next(null)
);
}

/**
* @description Initiate authentication via metamask.
*/
Expand All @@ -102,7 +140,10 @@ export class AuthService {

await this.sendSignedNonce(this.web3Service.address, nonce, signature);

this.fetchUser();
this.fetchUser().subscribe(user => {
this.$currentUser.next(user);
this.isAuthProcess = false;
});
this.headerStore.setUserMenuOpeningStatus(false);
}

Expand Down
17 changes: 1 addition & 16 deletions src/app/core/services/auth/models/user.interface.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,5 @@
export interface UserInterface {
isLogout?: boolean;
balance: number;
eos_balance: number;
visibleBalance: string;
contracts: number;
eos_address: string;
id: number;
internal_address: string;
internal_btc_address: string;
is_social: boolean;
lang: string;
memo: string;
use_totp: boolean;
username: string;
is_ghost?: boolean;
is_swaps_admin?: any;
address: string;
}

export interface AuthUserInterface {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import Web3 from 'web3';
import { BehaviorSubject } from 'rxjs';
// @ts-ignore
import config from '../../../../../test/enviroment.test.json';
import config from '../../../../../../test/enviroment.test.json';
import { BlockchainsInfo } from '../../blockchain-info';
import { BLOCKCHAIN_NAME } from '../../../../../shared/models/blockchain/BLOCKCHAIN_NAME';
import { IBlockchain } from '../../../../../shared/models/blockchain/IBlockchain';

/**
* Stub for unit tests.
Expand All @@ -13,6 +15,8 @@ export default () => {

return {
web3,
onAddressChanges: new BehaviorSubject<string>(undefined),
onNetworkChanges: new BehaviorSubject<IBlockchain>(undefined),
get address() {
return config.testWallet.address;
},
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// @ts-ignore
import config from '../../../../test/enviroment.test.json';
import config from '../../../../../test/enviroment.test.json';
import { BLOCKCHAIN_NAME } from '../../../../shared/models/blockchain/BLOCKCHAIN_NAME';

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { MetamaskProviderService } from '../private-provider/metamask-provider/m
import providerServiceStub from '../private-provider/metamask-provider/metamask-provider.service.stub';

// @ts-ignore
import config from '../../../../test/enviroment.test.json';
import config from '../../../../../test/enviroment.test.json';
import { PublicProviderService } from '../public-provider/public-provider.service';
import publicProviderServiceStub from '../public-provider/public-provider-service-stub';
import { Web3PublicService } from '../web3-public-service/web3-public.service';
Expand Down Expand Up @@ -35,8 +35,8 @@ describe('Web3ApiService', () => {
});
originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 60000;
service = TestBed.get(Web3PrivateService);
web3PublicEth = TestBed.get(Web3PublicService)[BLOCKCHAIN_NAME.ETHEREUM];
service = TestBed.get(Web3PrivateService);
});

afterEach(() => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,14 +84,18 @@ export class Web3PrivateService {
amount: string | BigNumber,
options: {
onTransactionHash?: (hash: string) => void;
gas?: string;
} = {}
): Promise<TransactionReceipt> {
const contract = new this.web3.eth.Contract(ERC20_TOKEN_ABI as any[], contractAddress);

return new Promise((resolve, reject) => {
contract.methods
.transfer(toAddress, amount.toString())
.send({ from: this.address, ...(this.defaultMockGas && { gas: this.defaultMockGas }) })
.send({
from: this.address,
...((options.gas || this.defaultMockGas) && { gas: options.gas || this.defaultMockGas })
})
.on('transactionHash', options.onTransactionHash || (() => {}))
.on('receipt', resolve)
.on('error', err => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { PublicProviderService } from '../public-provider/public-provider.servic

import { Web3Public } from './Web3Public';
// @ts-ignore
import config from '../../../../test/enviroment.test.json';
import config from '../../../../../test/enviroment.test.json';
import publicProviderServiceStub from '../public-provider/public-provider-service-stub';

import ERC20_TOKEN_ABI from '../constants/erc-20-abi';
Expand Down
9 changes: 5 additions & 4 deletions src/app/features/bridge-page/services/BridgeTransaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export class BridgeTransaction {
public depositAddress: string,
public amount: BigNumber,
public toAddress: string,
public web3Api: Web3PrivateService
public web3Private: Web3PrivateService
) {}

public async sendDeposit(onTransactionHash?: (hash: string) => void): Promise<void> {
Expand All @@ -41,14 +41,15 @@ export class BridgeTransaction {
const realAmount = this.amount.multipliedBy(10 ** decimals);

if (tokenAddress) {
this.receipt = await this.web3Api.transferTokens(
const estimatedGas = '120000'; // TODO: хотфикс сломавшегося в метамаске рассчета газа. Estimated gas не подойдет, т.к. в BSC не работает rpc
this.receipt = await this.web3Private.transferTokens(
tokenAddress,
this.depositAddress,
realAmount.toFixed(0),
{ onTransactionHash }
{ onTransactionHash, gas: estimatedGas }
);
} else {
this.receipt = await this.web3Api.sendTransaction(
this.receipt = await this.web3Private.sendTransaction(
this.depositAddress,
realAmount.toFixed(0),
{ onTransactionHash, inWei: true }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -157,9 +157,7 @@ describe('UniswapServiceService', () => {

const fromAmount = new BigNumber(2);
const trade = await service.calculateTrade(fromAmount, WEENUS, YEENUS);
const percentSlippage = new BigNumber(UniSwapService.slippageTolerance.toSignificant(10)).div(
100
);
const percentSlippage = UniSwapService.slippageTolerance;

const outputMinAmount = trade.to.amount.multipliedBy(new BigNumber(1).minus(percentSlippage));

Expand Down Expand Up @@ -202,9 +200,7 @@ describe('UniswapServiceService', () => {
);

const trade = await service.calculateTrade(fromAmount, WEENUS, YEENUS);
const percentSlippage = new BigNumber(UniSwapService.slippageTolerance.toSignificant(10)).div(
100
);
const percentSlippage = UniSwapService.slippageTolerance;
const outputMinAmount = trade.to.amount.multipliedBy(new BigNumber(1).minus(percentSlippage));

const callbackObject = {
Expand Down Expand Up @@ -236,9 +232,7 @@ describe('UniswapServiceService', () => {
it('create eth-tokens trade', async done => {
const fromAmount = new BigNumber(0.05);
const trade = await service.calculateTrade(fromAmount, ETH, YEENUS);
const percentSlippage = new BigNumber(UniSwapService.slippageTolerance.toSignificant(10)).div(
100
);
const percentSlippage = UniSwapService.slippageTolerance;
const outputMinAmount = trade.to.amount.multipliedBy(new BigNumber(1).minus(percentSlippage));

const callbackObject = {
Expand Down Expand Up @@ -266,9 +260,7 @@ describe('UniswapServiceService', () => {

const fromAmount = new BigNumber(30);
const trade = await service.calculateTrade(fromAmount, WEENUS, ETH);
const percentSlippage = new BigNumber(UniSwapService.slippageTolerance.toSignificant(10)).div(
100
);
const percentSlippage = UniSwapService.slippageTolerance;
const outputMinAmount = trade.to.amount.multipliedBy(new BigNumber(1).minus(percentSlippage));

let gasFee = new BigNumber(0);
Expand Down Expand Up @@ -321,9 +313,7 @@ describe('UniswapServiceService', () => {
);

const trade = await service.calculateTrade(fromAmount, WEENUS, ETH);
const percentSlippage = new BigNumber(UniSwapService.slippageTolerance.toSignificant(10)).div(
100
);
const percentSlippage = UniSwapService.slippageTolerance;
const outputMinAmount = trade.to.amount.multipliedBy(new BigNumber(1).minus(percentSlippage));

const callbackObject = {
Expand Down

0 comments on commit 79e18f9

Please sign in to comment.