Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: use middleware api wrapper from new sdk and update deps #1557

Merged
merged 3 commits into from
May 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
296 changes: 111 additions & 185 deletions backend/package-lock.json

Large diffs are not rendered by default.

10 changes: 5 additions & 5 deletions backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,12 @@
"private": true,
"license": "ISC",
"dependencies": {
"socket.io": "^4.7.2",
"web-push": "^3.6.6"
"socket.io": "^4.7.5",
"web-push": "^3.6.7"
},
"devDependencies": {
"chai": "^4.3.10",
"mocha": "^10.2.0",
"socket.io-client": "^4.7.2"
"chai": "^5.1.1",
"mocha": "^10.4.0",
"socket.io-client": "^4.7.5"
}
}
5 changes: 4 additions & 1 deletion backend/src/server.tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,10 @@ describe('leader interface', () => {

it('get all followers', async () => {
const [, leader] = await leaderWithOneFollower();
leader.emit('get-all-followers', expect({ [FOLLOWER_KEY]: { connected: true } }).to.be.equal);
const fs = await new Promise((resolve) => {
leader.emit('get-all-followers', resolve);
});
expect({ [FOLLOWER_KEY]: { connected: true } }).to.be.eql(fs);
});
});

Expand Down
537 changes: 277 additions & 260 deletions package-lock.json

Large diffs are not rendered by default.

30 changes: 15 additions & 15 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,21 +24,21 @@
"@aeternity/hd-wallet": "^0.2.0",
"@aeternity/ledger-app-api": "^0.2.2",
"@download/blockies": "^1.0.3",
"@ledgerhq/hw-transport-webusb": "6.28.1",
"@zxing/library": "^0.20.0",
"@ledgerhq/hw-transport-webusb": "6.28.6",
"@zxing/library": "^0.21.0",
"bignumber.js": "^9.1.2",
"bluebird": "^3.7.2",
"buffer": "^6.0.3",
"copy-to-clipboard": "^3.3.3",
"emoji-datasource-apple": "^15.0.1",
"emoji-datasource-apple": "^15.1.2",
"focus-visible": "^5.2.0",
"lodash-es": "^4.17.21",
"normalize.css": "^8.0.1",
"register-service-worker": "^1.7.2",
"rlp": "^3.0.0",
"rxjs": "^7.8.1",
"rxjs-etc": "^10.6.2",
"socket.io-client": "^4.7.2",
"socket.io-client": "^4.7.5",
"stream-browserify": "^3.0.0",
"swagger-client": "~3.19.7",
"util": "^0.12.5",
Expand All @@ -52,11 +52,11 @@
"vue-rx": "^6.2.0",
"vuex": "3.3.0",
"vuex-router-sync": "^5.0.0",
"workbox-precaching": "^7.0.0"
"workbox-precaching": "^7.1.0"
},
"devDependencies": {
"@babel/eslint-parser": "^7.23.3",
"@babel/plugin-syntax-import-attributes": "^7.23.3",
"@babel/eslint-parser": "^7.24.6",
"@babel/plugin-syntax-import-attributes": "^7.24.6",
"@frsource/cypress-plugin-visual-regression-diff": "^3.3.10",
"@intlify/eslint-plugin-vue-i18n": "^2.0.0",
"@vue/cli-plugin-babel": "^5.0.8",
Expand All @@ -73,22 +73,22 @@
"cordova": "^12.0.0",
"cordova-android": "^12.0.1",
"cordova-ios": "^7.0.1",
"cypress": "^13.6.2",
"cypress": "^13.10.0",
"eslint": "^8.56.0",
"eslint-plugin-vue": "^9.19.2",
"eslint-plugin-vuejs-accessibility": "^2.2.0",
"eslint-plugin-vue": "^9.26.0",
"eslint-plugin-vuejs-accessibility": "^2.3.0",
"jest": "^29.7.0",
"jest-canvas-mock": "^2.5.2",
"sass": "^1.69.7",
"sass-loader": "^13.3.3",
"serve": "^14.2.1",
"sass": "^1.77.2",
"sass-loader": "^14.2.1",
"serve": "^14.2.3",
"svg-url-loader": "^8.0.0",
"svgo": "^3.2.0",
"svgo": "^3.3.2",
"svgo-loader": "^4.0.0",
"vue-cli-plugin-i18n": "^2.3.2",
"vue-i18n-extract": "2.0.7",
"vue-template-compiler": "^2.7.16",
"webpack": "^5.89.0"
"webpack": "^5.91.0"
},
"browserslist": [
"> 1%",
Expand Down
13 changes: 3 additions & 10 deletions src/lib/methods.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import Swagger from 'swagger-client';

export async function resetConfirm() {
await this.$store.dispatch('modals/open', {
name: 'confirm',
Expand All @@ -12,17 +10,12 @@ export async function resetConfirm() {
}

export async function fetchAuctions(handler) {
const { state: { sdk: sdkPromise }, getters: { currentNetwork } } = this.$store;
const sdk = await Promise.resolve(sdkPromise);
const res = await sdk.middleware2.api.getNamesAuctions({ limit: 100 });
const { middleware } = this.$store.getters;
const res = await middleware.getNamesAuctions({ limit: 100 });
let { next } = res;
handler(res.data);
while (next) {
const url = currentNetwork.middlewareUrl + next;
const r = sdk.middleware2.responseInterceptor(
// eslint-disable-next-line no-await-in-loop
await Swagger.serializeRes(await fetch(url), url),
).body;
const r = middleware.getNamesAuctions({ overridePath: next });
handler(r.data);
next = r.next;
}
Expand Down
6 changes: 4 additions & 2 deletions src/lib/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,10 @@ export const isNotFoundError = (error) => error.statusCode === 404;

export const isInternalServerError = (error) => [500, 503].includes(error.statusCode);

export const isAccountNotFoundError = (error) => isNotFoundError(error)
&& get(error, 'response.body.reason') === 'Account not found';
export const isAccountNotFoundError = (error) => isNotFoundError(error) && (
get(error, 'response.body.reason') === 'Account not found'
|| error.message.includes('Account not found')
);

export class ConvertibleToString {
constructor(toString) {
Expand Down
18 changes: 11 additions & 7 deletions src/pages/aens/AuctionDetails.vue
Original file line number Diff line number Diff line change
Expand Up @@ -89,20 +89,24 @@ export default {
);
},
methods: {
async updateAuctionEntry() {
const { endsAt } = await this.$store.getters.node.getAuctionEntryByName(this.name);
this.endsAt = endsAt;
const nameId = produceNameId(this.name);
const sdk = await Promise.resolve(this.$store.state.sdk);
// TODO: show more than 100 bids
this.bids = (await sdk.middleware2.api.getAccountActivities(nameId, { limit: 100 })).data
async updateEndsAt() {
this.endsAt = (await this.$store.getters.node.getAuctionEntryByName(this.name)).endsAt;
},
async updateBids() {
const { data } = await this.$store.getters.middleware
// TODO: show more than 100 bids
.getAccountActivities(produceNameId(this.name), { limit: 100 });
this.bids = data
.filter(({ type }) => type === 'NameClaimEvent')
.filter(({ payload: { sourceTxType } }) => sourceTxType === 'NameClaimTx')
.map(({ payload: { tx: { accountId, nameFee } } }) => ({
nameFee: new BigNumber(nameFee).shiftedBy(-MAGNITUDE),
accountId,
}));
},
async updateAuctionEntry() {
await Promise.all([this.updateEndsAt(), this.updateBids()]);
},
blocksToRelativeTime,
},
};
Expand Down
3 changes: 1 addition & 2 deletions src/pages/aens/NameDetails.vue
Original file line number Diff line number Diff line change
Expand Up @@ -109,8 +109,7 @@ export default {
}
},
async goToTransactionDetails() {
const { hash } = await this.$store.state.sdk.middleware2.api
.getTx(this.details.createdAtTxIdx);
const { hash } = await this.$store.getters.middleware.getTx(this.details.createdAtTxIdx);
await this.$router.push(ENV_MOBILE_DEVICE
? { name: 'transaction-details', params: { hash } }
: `${this.currentNetwork.explorerUrl}/transactions/${hash}`);
Expand Down
8 changes: 3 additions & 5 deletions src/pages/aens/NameList.vue
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,6 @@ export default {
methods: {
fetchAuctions,
async fetchUserAuctions() {
const sdk = await Promise.resolve(this.$store.state.sdk);
const addresses = this.$store.state.accounts.list.map(({ address }) => address);
const [auctions, ...claims] = await Promise.all([
new Promise((resolve) => {
Expand All @@ -88,10 +87,9 @@ export default {
else acc.push(...arr);
});
}),
...addresses.map((account) => sdk
.middleware2.api.getTxs({
direction: 'backward', account, limit: 100, type: 'name_claim',
})),
...addresses.map((account) => this.$store.getters.middleware.getTxs({
direction: 'backward', account, limit: 100, type: ['name_claim'],
})),
]);
const claimIdxs = claims.map(({ data }) => data).flat(1).map(({ txIndex }) => txIndex);
this.auctions = auctions
Expand Down
5 changes: 2 additions & 3 deletions src/store/modules/accounts/hdWallet.js
Original file line number Diff line number Diff line change
Expand Up @@ -80,9 +80,8 @@ export default {
},

actions: {
async isAccountUsed({ rootState: { sdk } }, address) {
const { api } = sdk.then ? await sdk : sdk;
return api.getAccountByPubkey(address).then(() => true, () => false);
async isAccountUsed({ rootGetters: { node } }, address) {
return node.getAccountByPubkey(address).then(() => true, () => false);
},

async checkPreviousAndCreate({ dispatch, rootGetters }) {
Expand Down
5 changes: 2 additions & 3 deletions src/store/modules/accounts/hdWalletRemote.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,8 @@ export default {
},

actions: {
async isAccountUsed({ rootState: { sdk } }, address) {
const { api } = sdk.then ? await sdk : sdk;
return api.getAccountByPubkey(address).then(() => true, () => false);
async isAccountUsed({ rootGetters: { node } }, address) {
return node.getAccountByPubkey(address).then(() => true, () => false);
},

async checkPreviousAndCreate({ dispatch, rootGetters }) {
Expand Down
31 changes: 29 additions & 2 deletions src/store/modules/root.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,37 @@
/* eslint no-param-reassign: ["error", { "ignorePropertyModificationsFor": ["state"] }] */

import Vue from 'vue';
import { update, mergeWith } from 'lodash-es';
import { Node } from '@aeternity/aepp-sdk-next';
import {
update, mergeWith, isPlainObject, camelCase,
} from 'lodash-es';
import { Node, _Middleware } from '@aeternity/aepp-sdk-next';
import networksRegistry from '../../lib/networksRegistry';
import { genRandomBuffer } from '../utils';

class Middleware extends _Middleware {
async sendOperationRequest(args, spec) {
// TODO: remove after fixing https://github.com/aeternity/aepp-sdk-js/issues/1986
if (args.options?.limit) this.limit = args.options?.limit;
const res = await super.sendOperationRequest(
args,
args.options?.overridePath ? { ...spec, path: args.options.overridePath } : spec,
);
delete this.limit;

// TODO: remove after fixing https://github.com/aeternity/aepp-sdk-js/issues/1985
function mapKeysDeep(object, handler) {
if (Array.isArray(object)) return object.map((el) => mapKeysDeep(el, handler));
if (isPlainObject(object)) {
const entries = Object.entries(object)
.map(([key, value]) => [handler(key), mapKeysDeep(value, handler)]);
return Object.fromEntries(entries);
}
return object;
}
return mapKeysDeep(res, camelCase);
}
}

const getAppByHost = (apps, appHost) => apps.find(({ host }) => host === appHost);

export default {
Expand Down Expand Up @@ -33,6 +59,7 @@ export default {
},
getApp: ({ apps }) => getAppByHost.bind(null, apps),
node: (_, { currentNetwork }) => new Node(currentNetwork.url),
middleware: (_, { currentNetwork }) => new Middleware(currentNetwork.middlewareUrl),
},

mutations: {
Expand Down
75 changes: 31 additions & 44 deletions src/store/plugins/initSdk.js
Original file line number Diff line number Diff line change
Expand Up @@ -81,49 +81,37 @@ export default (store) => {
};

const acceptCb = (_, { accept }) => accept();
const [sdk, middleware2] = await Promise.all([
Ae.compose(ChainNode, Transaction, Contract, Aens, WalletRPC, { methods })({
nodes: [{
name: network.name,
instance: await Node({ url: network.url, ignoreVersion: true }),
}],
name: 'Base Aepp',
onConnection: acceptCb,
async onSubscription(_, { accept }, origin) {
const activeAccount = await this.address(this.getApp(origin));
accept({
accounts: {
current: { [activeAccount]: {} },
connected: Object.fromEntries(
store.state.accounts.list
.filter(({ address }) => address !== activeAccount)
.map(({ address }) => [address, {}]),
),
},
});
},
async onSign(_, { accept }) {
accept(null, {
onAccount: { sign: () => {}, address: () => {} },
});
},
onMessageSign: acceptCb,
onAskAccounts: acceptCb,
onDisconnect() {
Object.keys(this.rpcClients).forEach((id) => this.removeRpcClient(id));
},
}),
(async () => {
const specUrl = `${network.middlewareUrl}/v2/api`;
const spec = await fetchJson(specUrl);
spec.paths['/status'].parameters ??= []; // bug in @aeternity/[email protected]
// TODO: remove after solving https://github.com/aeternity/ae_mdw/issues/1759
if (network.middlewareUrl === 'http://localhost:4000') {
spec.servers[0].url = spec.servers[0].url.replace('/mdw', '');
}
return genSwaggerClient(specUrl, { spec });
})(),
]);
const sdk = await Ae.compose(ChainNode, Transaction, Contract, Aens, WalletRPC, { methods })({
nodes: [{
name: network.name,
instance: await Node({ url: network.url, ignoreVersion: true }),
}],
name: 'Base Aepp',
onConnection: acceptCb,
async onSubscription(_, { accept }, origin) {
const activeAccount = await this.address(this.getApp(origin));
accept({
accounts: {
current: { [activeAccount]: {} },
connected: Object.fromEntries(
store.state.accounts.list
.filter(({ address }) => address !== activeAccount)
.map(({ address }) => [address, {}]),
),
},
});
},
async onSign(_, { accept }) {
accept(null, {
onAccount: { sign: () => {}, address: () => {} },
});
},
onMessageSign: acceptCb,
onAskAccounts: acceptCb,
onDisconnect() {
Object.keys(this.rpcClients).forEach((id) => this.removeRpcClient(id));
},
});
// TODO: remove after updating sdk
sdk.Ae.defaults.verify = false;

Expand All @@ -138,7 +126,6 @@ export default (store) => {
}

sdk.selectNode(network.name);
sdk.middleware2 = middleware2;
return sdk;
};

Expand Down
Loading
Loading