Skip to content

Commit

Permalink
Merge pull request #1581 from aeternity/update-sdk-14
Browse files Browse the repository at this point in the history
chore: use next sdk everywhere except aepps connection
  • Loading branch information
davidyuk authored Feb 14, 2025
2 parents b4f5f1c + 602e273 commit b6277aa
Show file tree
Hide file tree
Showing 23 changed files with 135 additions and 80 deletions.
12 changes: 8 additions & 4 deletions src/components/ConnectionStatus.vue
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,13 @@ export default {
computed: mapState({
message({ onLine, sdk }) {
if (!onLine) return { text: this.$t('network.connection-status.offline') };
if (!sdk) return { text: this.$t('network.connection-status.no-sdk') };
if (sdk.then)
return { text: this.$t('network.connection-status.connecting'), className: 'connecting' };
const { networkId } = this.$store.state.sdkSync;
switch (networkId) {
case '_cant-connect':
return { text: this.$t('network.connection-status.cant-connect') };
case '_connecting':
return { text: this.$t('network.connection-status.connecting'), className: 'connecting' };
}
if (!this.middlewareStatus) {
return {
text: this.$t('network.connection-status.middleware.unavailable'),
Expand All @@ -32,7 +36,7 @@ export default {
className: 'connecting',
};
}
if (process.env.NODE_ENV === 'production' && sdk.getNetworkId() !== 'ae_mainnet') {
if (process.env.NODE_ENV === 'production' && networkId !== 'ae_mainnet') {
return {
text: this.$t('network.connection-status.connected-to-testnet'),
className: 'test-net',
Expand Down
2 changes: 1 addition & 1 deletion src/locales/cn.json
Original file line number Diff line number Diff line change
Expand Up @@ -556,7 +556,7 @@
"network": {
"connection-status": {
"offline": "您已离线,请检查您的网络连接。",
"no-sdk": "我们无法连接到您选择的节点。",
"cant-connect": "我们无法连接到您选择的节点。",
"connecting": "正在连接网络中...",
"connected-to-testnet": "您已连接到测试网。",
"middleware": {
Expand Down
2 changes: 1 addition & 1 deletion src/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -556,7 +556,7 @@
"network": {
"connection-status": {
"offline": "You are offline... Please check your connection.",
"no-sdk": "We are unable to connect to the chosen node.",
"cant-connect": "We are unable to connect to the chosen node.",
"connecting": "Connecting to the network...",
"connected-to-testnet": "You are connected to a testnet.",
"middleware": {
Expand Down
2 changes: 1 addition & 1 deletion src/locales/es.json
Original file line number Diff line number Diff line change
Expand Up @@ -556,7 +556,7 @@
"network": {
"connection-status": {
"offline": "Estás desconectado... Comprueba tu conexión",
"no-sdk": "No podemos conectarnos al nodo elegido",
"cant-connect": "No podemos conectarnos al nodo elegido",
"connecting": "Conectando a la red...",
"connected-to-testnet": "Está conectado a una red de prueba",
"middleware": {
Expand Down
2 changes: 1 addition & 1 deletion src/locales/ru.json
Original file line number Diff line number Diff line change
Expand Up @@ -556,7 +556,7 @@
"network": {
"connection-status": {
"offline": "Вы не в сети... Пожалуйста, проверьте ваше подключение к интернету.",
"no-sdk": "Мы не можем подключиться к выбранному узлу.",
"cant-connect": "Мы не можем подключиться к выбранному узлу.",
"connecting": "Подключаемся к сети...",
"connected-to-testnet": "Вы подключены к тестовой сети.",
"middleware": {
Expand Down
5 changes: 4 additions & 1 deletion src/pages/aens/AuctionBid.vue
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@
import { pick, debounce } from 'lodash-es';
import BigNumber from 'bignumber.js';
import { mapGetters } from 'vuex';
import { Name } from '@aeternity/aepp-sdk-next';
import { MAGNITUDE } from '../../lib/constants';
import blocksToRelativeTime from '../../filters/blocksToRelativeTime';
import Page from '../../components/Page.vue';
Expand Down Expand Up @@ -144,7 +145,9 @@ export default {
}
this.busy = true;
try {
await this.$store.state.sdk.aensBid(name, BigNumber(this.amount).shiftedBy(MAGNITUDE));
await new Name(name, this.$store.getters.sdk.getContext()).bid(
BigNumber(this.amount).shiftedBy(MAGNITUDE),
);
this.$store.dispatch('modals/open', {
name: 'notification',
text: i18n.t('name.new.notification.bid', { name }),
Expand Down
11 changes: 4 additions & 7 deletions src/pages/aens/NameList.vue
Original file line number Diff line number Diff line change
Expand Up @@ -61,10 +61,7 @@ export default {
NamePending,
ButtonAddFixed,
},
data: () => ({
auctions: [],
height: null,
}),
data: () => ({ auctions: [] }),
computed: mapState('names', ['owned']),
async mounted() {
const fetchNames = () => this.$store.dispatch('names/fetchOwned');
Expand All @@ -90,17 +87,17 @@ export default {
}),
),
);
this.height ??= await this.$store.state.sdk.height();
const height = await this.$store.getters.sdk.getHeight({ cached: true });
const recentlyClaimedNames = uniq(
claims
.map(({ data }) => data)
.flat()
// max auction length is 29760 blocks, but it can be increased multiple times by 120
.filter(({ blockHeight }) => blockHeight > this.height - 40000)
.filter(({ blockHeight }) => blockHeight > height - 40000)
.map(({ tx: { name } }) => name.toLowerCase())
.filter((name) => isNameValid(name) && isAuctionName(name)),
);
const nodeNoRetry = new Node(this.$store.state.sdkUrl, { retryCount: 0 });
const nodeNoRetry = new Node(this.$store.getters.node.$host, { retryCount: 0 });
this.auctions = (
await Promise.allSettled(
recentlyClaimedNames.map((name) =>
Expand Down
12 changes: 6 additions & 6 deletions src/pages/aens/NameNew.vue
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@

<script>
import { mapGetters } from 'vuex';
import { Name } from '@aeternity/aepp-sdk-next';
import { MAX_AUCTION_NAME_LENGTH } from '../../lib/constants';
import { handleUnknownError, isNotFoundError } from '../../lib/utils';
import { i18n } from '../../store/plugins/ui/languages';
Expand All @@ -62,7 +63,6 @@ export default {
async handleSubmit() {
if (!(await this.$validator.validateAll())) return;
this.busy = true;
let claimTxHash;
try {
await this.$store.getters.node.getAuctionEntryByName(this.name);
Expand All @@ -82,11 +82,11 @@ export default {
}
}
const name = new Name(this.name, this.$store.getters.sdk.getContext());
let claimTxHash;
try {
const { salt } = await this.$store.state.sdk.aensPreclaim(this.name);
claimTxHash = (await this.$store.state.sdk.aensClaim(this.name, salt, { waitMined: false }))
.hash;
await name.preclaim();
claimTxHash = (await name.claim({ waitMined: false })).hash;
this.$store.dispatch('modals/open', {
name: 'notification',
text: this.$t('name.new.notification.claim-sent', { name: this.name }),
Expand All @@ -102,7 +102,7 @@ export default {
try {
this.$store.dispatch('names/fetchOwned');
await this.$store.state.sdk.poll(claimTxHash);
await this.$store.getters.sdk.poll(claimTxHash);
const isAuction = MAX_AUCTION_NAME_LENGTH >= this.name.length;
if (!isAuction) {
await this.$store.dispatch('names/updatePointer', {
Expand Down
4 changes: 2 additions & 2 deletions src/pages/aens/NameTransfer.vue
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@
<script>
import { mapState, mapGetters } from 'vuex';
import { defer } from 'lodash-es';
import { Name } from '@aeternity/aepp-sdk-next';
import { handleUnknownError, getAddressByNameEntry } from '../../lib/utils';
import Page from '../../components/Page.vue';
import Guide from '../../components/Guide.vue';
Expand Down Expand Up @@ -149,8 +150,7 @@ export default {
address: this.accountTo,
});
} else {
if (this.$store.state.sdk.then) await this.$store.state.sdk;
await this.$store.state.sdk.aensTransfer(this.nameEntry.name, this.accountTo);
await new Name(this.name, this.$store.getters.sdk.getContext()).transfer(this.accountTo);
}
this.$store.dispatch('modals/open', {
name: 'notification',
Expand Down
2 changes: 1 addition & 1 deletion src/pages/desktop/Send.vue
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ export default {
const amount = BigNumber(this.amount);
this.busy = true;
try {
const { hash } = await this.$store.state.sdk.spend(
const { hash } = await this.$store.getters.sdk.spend(
amount.shiftedBy(MAGNITUDE),
this.accountTo,
);
Expand Down
4 changes: 2 additions & 2 deletions src/pages/desktop/Settings.vue
Original file line number Diff line number Diff line change
Expand Up @@ -123,8 +123,8 @@ export default {
}),
computed: {
...mapGetters(['currentNetwork']),
...mapState({
networkId: (state) => state.sdk && state.sdk.getNetworkId && state.sdk.getNetworkId(),
...mapState('sdkSync', {
networkId: ({ networkId }) => (networkId.startsWith('_') ? null : networkId),
}),
},
methods: {
Expand Down
2 changes: 1 addition & 1 deletion src/pages/mobile/AppBrowser.vue
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ export default {
},
},
async mounted() {
const sdk = this.$store.state.sdk.then ? await this.$store.state.sdk : this.$store.state.sdk;
const sdk = await this.$store.state.sdk;
const connection = BrowserWindowMessageConnection({ target: this.$refs.iframe.contentWindow });
sdk.addRpcClient(connection);
Expand Down
6 changes: 3 additions & 3 deletions src/pages/mobile/RedeemBalance.vue
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
<script>
import { pick } from 'lodash-es';
import BigNumber from 'bignumber.js';
import { encode, Encoding, MemoryAccount, Node, transferFunds } from '@aeternity/aepp-sdk-next';
import { encode, Encoding, MemoryAccount, transferFunds } from '@aeternity/aepp-sdk-next';
import { handleUnknownError } from '../../lib/utils';
import AeSpinner from '../../components/AeSpinner.vue';
import Page from '../../components/Page.vue';
Expand Down Expand Up @@ -97,7 +97,7 @@ export default {
const account = new MemoryAccount(
encode(privateKey.subarray(0, 32), Encoding.AccountSecretKey),
);
const sdk = this.$store.state.sdk.then ? await this.$store.state.sdk : this.$store.state.sdk;
const { sdk } = this.$store.getters;
this.balance = BigNumber(await sdk.getBalance(account.address)).shiftedBy(-MAGNITUDE);
if (this.balance < MIN_SPEND_TX_FEE) {
await this.$store.dispatch('modals/open', {
Expand All @@ -116,7 +116,7 @@ export default {
tx: { amount },
} = await transferFunds(1, accountTo, {
onAccount: this.inviteAccount,
onNode: new Node(this.$store.state.sdkUrl),
onNode: this.$store.getters.node,
});
this.$router.push({ name: 'transfer' });
this.$store.dispatch('modals/open', {
Expand Down
3 changes: 1 addition & 2 deletions src/pages/mobile/SendConfirm.vue
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,7 @@ export default {
denominator: 3,
});
const amount = BigNumber(this.amount);
if (this.$store.state.sdk.then) await this.$store.state.sdk;
const { hash } = await this.$store.state.sdk.spend(amount.shiftedBy(MAGNITUDE), this.to);
const { hash } = await this.$store.getters.sdk.spend(amount.shiftedBy(MAGNITUDE), this.to);
this.$router.push({ name: 'transfer' });
this.$store.dispatch('modals/open', {
Expand Down
2 changes: 2 additions & 0 deletions src/store/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import runMigrations from './migrations';
import persistState from './plugins/persistState';
import remoteConnection from './plugins/remoteConnection';
import initSdk from './plugins/initSdk';
import sdk from './plugins/sdk';
import registerServiceWorker from './plugins/registerServiceWorker';
import reverseIframe from './plugins/reverseIframe';
import syncLedgerAccounts from './plugins/syncLedgerAccounts';
Expand Down Expand Up @@ -81,6 +82,7 @@ export default new Vuex.Store({
}),
),
initSdk,
sdk,
...(RUNNING_IN_POPUP
? []
: [
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 @@ -314,12 +314,11 @@ export default {
return dispatch('signWithoutConfirmation', data);
},

async signTransaction({ dispatch, rootState }, { transaction, signal }) {
const sdk = rootState.sdk.then ? await rootState.sdk : rootState.sdk;
async signTransaction({ dispatch, rootGetters: { node } }, { transaction, signal }) {
const txWithFee = await dispatch('confirmTxSigning', { transaction, signal });
const signature = await dispatch(
'signWithoutConfirmation',
Buffer.concat([Buffer.from(sdk.getNetworkId()), decode(txWithFee)]),
Buffer.concat([Buffer.from(await node.getNetworkId()), decode(txWithFee)]),
);
return buildTx({ tag: Tag.SignedTx, encodedTx: txWithFee, signatures: [signature] });
},
Expand Down
32 changes: 1 addition & 31 deletions src/store/modules/root.js
Original file line number Diff line number Diff line change
@@ -1,38 +1,10 @@
/* eslint no-param-reassign: ["error", { "ignorePropertyModificationsFor": ["state"] }] */

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

class Middleware extends MiddlewareOriginal {
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, 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);
}
if (object?.data && object?.next && object?.prev) {
object.data = mapKeysDeep(object.data, handler);
return object;
}
return object;
}
return mapKeysDeep(res, camelCase);
}
}

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

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

mutations: {
Expand Down
4 changes: 2 additions & 2 deletions src/store/plugins/initSdk.js
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ export default (store) => {
async ([sdk, list]) => {
syncAccountsPromise = (async () => {
if (sdk == null) return;
if (sdk.then) await sdk.then;
await sdk;
store.commit('setSdkAccounts', list);
})();
await syncAccountsPromise;
Expand All @@ -161,7 +161,7 @@ export default (store) => {
store.watch(
(_state, getters) => getters['accounts/active']?.address,
async (address) => {
if (store.state.sdk.then) await store.state.sdk;
await store.state.sdk;
await syncAccountsPromise;
store.commit('selectSdkAccount', address);
},
Expand Down
4 changes: 2 additions & 2 deletions src/store/plugins/remoteConnection.js
Original file line number Diff line number Diff line change
Expand Up @@ -114,8 +114,8 @@ export default (store) => {

const getRpcPeer = memoize((followerId) => new RpcPeer((response) => socket.emit('message-to-follower', followerId, response), {
createAccount: () => store.dispatch('accounts/hdWallet/create'),
sign: markAbortable((data, options, signal) => store.state.sdk.sign(data, { ...options, signal })),
signTransaction: markAbortable((transaction, options, signal) => store.state.sdk.signTransaction(transaction, { ...options, signal })),
sign: markAbortable((data, options, signal) => store.getters.sdk.sign(data, { ...options, signal })),
signTransaction: markAbortable((transaction, options, signal) => store.getters.sdk.signTransaction(transaction, { ...options, signal })),
}));
socket.on(
'message-from-follower',
Expand Down
Loading

0 comments on commit b6277aa

Please sign in to comment.