Skip to content

Commit

Permalink
update acala.js history api
Browse files Browse the repository at this point in the history
  • Loading branch information
RomeroYang committed Dec 20, 2022
1 parent 4f99169 commit 7931d83
Show file tree
Hide file tree
Showing 7 changed files with 42 additions and 26 deletions.
6 changes: 3 additions & 3 deletions lib/api/assets/acalaServiceAssets.dart
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ class AcalaServiceAssets {

Future<List?> getAllTokenSymbols() async {
final List? res =
await plugin.sdk.webView!.evalJavascript('acala.getAllTokens(api)');
await plugin.sdk.webView!.evalJavascript('acala.getAllTokens()');
return res;
}

Expand Down Expand Up @@ -53,7 +53,7 @@ class AcalaServiceAssets {
final channel = '$tokenBalanceChannel${e.symbol}';
plugin.sdk.api.subscribeMessage(
'acala.getTokenBalance',
['api', address, e.tokenNameId],
[address, e.tokenNameId],
channel,
(Map data) {
callback({
Expand All @@ -80,7 +80,7 @@ class AcalaServiceAssets {
'$tokenBalanceChannel${lpToken.map((e) => e.symbol).join('')}';
plugin.sdk.api.subscribeMessage(
'acala.getTokenBalance',
['api', address, e.tokenNameId],
[address, e.tokenNameId],
channel,
(Map data) {
callback({
Expand Down
2 changes: 1 addition & 1 deletion lib/api/history/acalaServiceHistory.dart
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ class AcalaServiceHistory {
Future<List?> queryHistory(
String type, String? address, Map<String, dynamic> params) async {
final List? list = await plugin.sdk.webView!.evalJavascript(
'acala.getHistory(api,"$type","$address",${jsonEncode(params)})');
'acala.getHistory("$type","$address",${jsonEncode(params)})');
return list;
}
}
4 changes: 2 additions & 2 deletions lib/common/constants/base.dart
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ const plugin_name_acala = 'acala';
const ss58_prefix_acala = 10;

const GraphQLConfig = {
'defiUri': 'https://api.subquery.network/sq/AcalaNetwork/acala',
'loanUri': 'https://api.subquery.network/sq/AcalaNetwork/acala-loans',
'defiUri': 'https://api.polkawallet.io/acala-dex-subql',
'loanUri': 'https://api.polkawallet.io/acala-loan-subql',
"taigaUri": "https://api.subquery.network/sq/nutsfinance/tapio-protocol"
};
2 changes: 1 addition & 1 deletion lib/js_service_acala/dist/main.js

Large diffs are not rendered by default.

14 changes: 11 additions & 3 deletions lib/js_service_acala/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { WsProvider, ApiPromise, ApiRx } from "@polkadot/api";
import { EvmRpcProvider } from "@acala-network/eth-providers";
import { firstValueFrom } from "rxjs";
import { subscribeMessage, getNetworkConst, getNetworkProperties } from "./service/setting";
import keyring from "./service/keyring";
Expand Down Expand Up @@ -36,11 +37,9 @@ async function connect(nodes: string[]) {
(<any>window).apiRx = resRx;
// console.log(res);
const url = nodes[(<any>res)._options.provider.__private_59_endpointIndex];
await _initAcalaSDK(res, url);
send("log", `${url} wss connected success`);
resolve(url);

(<any>window).wallet = new Wallet(res, { wsProvider });
(<any>window).wallet.isReady;
} else {
res.disconnect();
const url = nodes[(<any>res)._options.provider.__private_59_endpointIndex];
Expand All @@ -55,6 +54,15 @@ async function connect(nodes: string[]) {
});
}

async function _initAcalaSDK(api: ApiPromise, url: string) {
const evmProvider = new EvmRpcProvider(url, {
maxBlockCacheSize: 1,
storageCacheSize: 100,
});
(<any>window).wallet = new Wallet(api, { evmProvider });
await (<any>window).wallet.isReady;
}

async function test() {}

(<any>window).settings = {
Expand Down
38 changes: 23 additions & 15 deletions lib/js_service_acala/src/service/acala.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { createDexShareName, FixedPointNumber, forceToCurrencyId, forceToCurrencyName, Token } from "@acala-network/sdk-core";
import { ApiPromise, ApiRx } from "@polkadot/api";
import { hexToString } from "@polkadot/util";
import { hexToString, BN_ZERO } from "@polkadot/util";
import { nft_image_config } from "../constants/acala";
import { BN } from "@polkadot/util/bn/bn";
import { AcalaDex, AggregateDex, NutsDex } from "@acala-network/sdk-swap";
Expand Down Expand Up @@ -60,6 +60,8 @@ function _getTokenSymbol(allTokens: any[], tokenNameId: string): string {
let swapper: AggregateDex;
async function _initDexSDK(api: ApiRx) {
const wallet = (<any>window).wallet;
await wallet.isReady;

swapper = new AggregateDex({
api,
wallet,
Expand Down Expand Up @@ -143,8 +145,11 @@ async function calcTokenSwapAmount(apiRx: ApiRx, input: number, output: number,
/**
* getAllTokens, with ForeignAssets
*/
async function getAllTokens(api: ApiPromise) {
const allTokens = await ((<any>window).wallet as Wallet).getTokens();
async function getAllTokens() {
const w = (<any>window).wallet as Wallet;
await w.isReady;

const allTokens = await w.getTokens();

return Object.values(allTokens)
.map((e) => {
Expand Down Expand Up @@ -187,8 +192,11 @@ function _getTokenType(token: Token) {
/**
* get token balance from acala wallet sdk
*/
async function getTokenBalance(api: ApiPromise, address: string, tokenNameId: string, callback: (value: any) => void) {
const sub = ((<any>window).wallet as Wallet).subscribeBalance(tokenNameId, address);
async function getTokenBalance(address: string, tokenNameId: string, callback: (value: any) => void) {
const w = (<any>window).wallet as Wallet;
await w.isReady;

const sub = w.subscribeBalance(tokenNameId, address);
if (!!callback) {
sub.subscribe({
next: (value: BalanceData) => {
Expand Down Expand Up @@ -382,7 +390,7 @@ async function _fetchCollateralRewards(api: ApiPromise, pool: any, address: stri
const res = (await Promise.all([
api.query.rewards.poolInfos({ Loans: pool }),
api.query.rewards.sharesAndWithdrawnRewards({ Loans: pool }, address),
getAllTokens(api),
getAllTokens(),
])) as any;
const pendingRewards = (!!api.query.incentives.pendingMultiRewards
? await api.query.incentives?.pendingMultiRewards({ Loans: pool }, address)
Expand Down Expand Up @@ -448,7 +456,7 @@ async function fetchDexPoolInfo(api: ApiPromise, pool: any, address: string) {
api.query.rewards.poolInfos({ Dex: pool }),
api.query.rewards.sharesAndWithdrawnRewards({ Dex: pool }, address),
api.query.tokens.totalIssuance(pool),
getAllTokens(api),
getAllTokens(),
])) as any;
const pendingRewards = (!!api.query.incentives.pendingMultiRewards
? await api.query.incentives?.pendingMultiRewards({ Dex: pool }, address)
Expand All @@ -460,13 +468,13 @@ async function fetchDexPoolInfo(api: ApiPromise, pool: any, address: string) {
const withdrawns = Array.from(res[2][1].entries()).map((entry) => {
const currencyId = forceToCurrencyId(api, entry[0]);
const tokenNameId = forceToCurrencyName(currencyId);
const amount = FPNum(entry[1].toString(), _getTokenDecimal(res[4], tokenNameId));
const amount = FPNum(entry[1]?.toString() || BN_ZERO, _getTokenDecimal(res[4], tokenNameId));
return { tokenNameId, amount };
});
const pendings = Array.from(pendingRewards.entries()).map((entry) => {
const currencyId = forceToCurrencyId(api, entry[0]);
const tokenNameId = forceToCurrencyName(currencyId);
const amount = FPNum(entry[1].toString(), _getTokenDecimal(res[4], tokenNameId));
const amount = FPNum(entry[1]?.toString() || BN_ZERO, _getTokenDecimal(res[4], tokenNameId));
return { tokenNameId, amount };
});
let saving = "0";
Expand Down Expand Up @@ -972,14 +980,14 @@ async function queryDexIncentiveLoyaltyEndBlock(api: ApiPromise) {
return { result, loyalty };
}

async function getHistory(api: ApiPromise, type: string, address: string, params: Object) {
async function getHistory(type: string, address: string, params: any) {
const history = new History({
fetchEndpoints: {
transfer: "https://api.subquery.network/sq/AcalaNetwork/acala-transfer",
swap: "https://api.subquery.network/sq/AcalaNetwork/acala-dex",
earn: "https://api.subquery.network/sq/AcalaNetwork/acala-incentives",
loan: "https://api.subquery.network/sq/AcalaNetwork/acala-loans",
homa: "https://api.subquery.network/sq/AcalaNetwork/acala-homa",
transfer: "https://api.polkawallet.io/acala-history-subql",
swap: "https://api.polkawallet.io/acala-dex-subql",
earn: "https://api.polkawallet.io/acala-history-subql",
loan: "https://api.polkawallet.io/acala-loan-subql",
homa: "https://api.polkawallet.io/acala-history-subql",
},
wallet: (<any>window).wallet as Wallet,
poolInterval: 5 * 60 * 1000,
Expand Down
2 changes: 1 addition & 1 deletion lib/service/serviceAssets.dart
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ class ServiceAssets {

Future<TokenBalanceData> updateTokenBalances(TokenBalanceData token) async {
final res = await plugin.sdk.webView!.evalJavascript(
'acala.getTokenBalance(api, "${keyring.current.address}", "${token.tokenNameId}")');
'acala.getTokenBalance("${keyring.current.address}", "${token.tokenNameId}")');

final balances =
Map<String?, TokenBalanceData>.from(store!.assets.tokenBalanceMap);
Expand Down

0 comments on commit 7931d83

Please sign in to comment.