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

Update to sdk@13 partially #1497

Merged
merged 4 commits into from
May 5, 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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
node_modules
/dist
__image_snapshots_local__
tests/e2e/fixtures/qr-code-videos/video.y4m

# Cordova files
/www
Expand Down
24 changes: 24 additions & 0 deletions cypress.config.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
const path = require('path');
const fs = require('fs');
const { defineConfig } = require('cypress');
// TODO: remove after fixing https://github.com/import-js/eslint-plugin-import/issues/1810
// eslint-disable-next-line import/no-unresolved
Expand All @@ -17,6 +19,28 @@ module.exports = defineConfig({
experimentalRunAllSpecs: true,
setupNodeEvents(on, config) {
initPlugin(on, config);

const videoPath = path.resolve('tests/e2e/fixtures/qr-code-videos/video.y4m');
const defaultVideoPath = path.resolve('tests/e2e/fixtures/qr-code-videos/default.y4m');

on('before:browser:launch', (browser, launchOptions) => {
if (fs.existsSync(videoPath)) fs.unlinkSync(videoPath);
fs.linkSync(defaultVideoPath, videoPath);

if (browser.family === 'chromium' && browser.name !== 'electron') {
launchOptions.args.push(`--use-file-for-fake-video-capture=${videoPath}`);
}
return launchOptions;
});

on('task', {
changeVideoSource(videoSource) {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

const sourceVideoPath = path.join('tests/e2e/fixtures/qr-code-videos', videoSource);
fs.unlinkSync(videoPath);
fs.linkSync(sourceVideoPath, videoPath);
return null;
},
});
},
},
});
4 changes: 2 additions & 2 deletions src/components/AeInputAccount.vue
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@

<script>
import { mapState } from 'vuex';
import { Crypto } from '@aeternity/aepp-sdk';
import { isAddressValid } from '@aeternity/aepp-sdk-next';
import { AENS_DOMAIN } from '../lib/constants';
import withFormatting from '../lib/withFormatting';
import removeSpacesOnCopy from '../directives/removeSpacesOnCopy';
Expand Down Expand Up @@ -96,7 +96,7 @@ const formatAddress = (address) => {
const AeTextareaFormatted = withFormatting(AeTextarea, {
formatDisplayValueAndCursor({ value, cursor }, previousValue) {
if (ADDRESS_PREFIX.startsWith(value)) return { value, cursor };
const name = Crypto.isAddressValid(value) && this.$store.getters['names/get'](value, false);
const name = isAddressValid(value) && this.$store.getters['names/get'](value, false);
if (name) return { value: name, cursor: 0 };
if (value.startsWith(ADDRESS_PREFIX)) {
const withoutChain = value.replace(new RegExp(`\\${AENS_DOMAIN}$`), '');
Expand Down
29 changes: 13 additions & 16 deletions src/components/mobile/ConfirmTransactionSignModal.vue
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@

<DetailsList
:object="transaction"
:field-renderers="TX_FIELDS"
:field-renderers="fieldRenderers"
/>

<AeButtonGroup slot="footer">
Expand All @@ -60,7 +60,7 @@

<script>
import { mapState } from 'vuex';
import { SCHEMA } from '@aeternity/aepp-sdk';
import { Tag } from '@aeternity/aepp-sdk-next';
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why next?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would rename it back to @aeternity/aepp-sdk after finishing the update

import Page from '../Page.vue';
import Guide from '../Guide.vue';
import AeFraction from '../AeFraction.vue';
Expand Down Expand Up @@ -96,8 +96,7 @@ export default {
data() {
return {
newFee: this.transaction.fee,
TX_TYPE: SCHEMA.TX_TYPE,
TX_FIELDS: {
fieldRenderers: {
payload: Payload,
recipientId: RecipientId,
code: Code,
Expand All @@ -119,23 +118,21 @@ export default {
...mapState({
stepFraction: (state) => (ENV_MOBILE_DEVICE ? state.mobile.stepFraction : null),
}),
txType() {
return SCHEMA.OBJECT_ID_TX_TYPE[this.transaction.tag];
},
guideTemplate() {
if (this.txType === SCHEMA.TX_TYPE.spend) return this.$t('modal.confirm-transaction-sign.guide-spend');
if (this.txType === SCHEMA.TX_TYPE.nameClaim && !+this.transaction.nameSalt) {
const { tag } = this.transaction;
if (tag === Tag.SpendTx) return this.$t('modal.confirm-transaction-sign.guide-spend');
if (tag === Tag.NameClaimTx && !+this.transaction.nameSalt) {
return this.$t('modal.confirm-transaction-sign.guide-name-bid');
}
return this.$t('modal.confirm-transaction-sign.guide', {
title: {
[SCHEMA.TX_TYPE.contractCreate]: this.$t('modal.confirm-transaction-sign.contract-create'),
[SCHEMA.TX_TYPE.contractCall]: this.$t('modal.confirm-transaction-sign.contract-call'),
[SCHEMA.TX_TYPE.namePreClaim]: this.$t('modal.confirm-transaction-sign.name-pre-claim'),
[SCHEMA.TX_TYPE.nameClaim]: this.$t('modal.confirm-transaction-sign.name-claim'),
[SCHEMA.TX_TYPE.nameUpdate]: this.$t('modal.confirm-transaction-sign.name-update'),
[SCHEMA.TX_TYPE.nameTransfer]: this.$t('modal.confirm-transaction-sign.name-transfer'),
}[this.txType] || '',
[Tag.ContractCreateTx]: this.$t('modal.confirm-transaction-sign.contract-create'),
[Tag.ContractCallTx]: this.$t('modal.confirm-transaction-sign.contract-call'),
[Tag.NamePreclaimTx]: this.$t('modal.confirm-transaction-sign.name-pre-claim'),
[Tag.NameClaimTx]: this.$t('modal.confirm-transaction-sign.name-claim'),
[Tag.NameUpdateTx]: this.$t('modal.confirm-transaction-sign.name-update'),
[Tag.NameTransferTx]: this.$t('modal.confirm-transaction-sign.name-transfer'),
}[tag] || '',
});
},
maxFee() {
Expand Down
4 changes: 2 additions & 2 deletions src/components/mobile/details-fields.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { TxBuilderHelper } from '@aeternity/aepp-sdk';
import { decode, Encoding } from '@aeternity/aepp-sdk-next';
import { i18n } from '../../store/plugins/ui/languages';
import DetailsRawData from './DetailsRawData.vue';
import DetailsAddress from './DetailsAddress.vue';
Expand Down Expand Up @@ -26,7 +26,7 @@ export const genDetailsAmountCurrency = genDetailsWrapper(DetailsAmountCurrency,
export const Payload = {
functional: true,
render: (createElement, { props: { value } }) => {
const data = TxBuilderHelper.decode(value, 'ba').toString();
const data = decode(value, Encoding.Bytearray).toString();
return data
? createElement(DetailsRawData, {
attrs: { name: i18n.t('modal.confirm-transaction-sign.payload'), data },
Expand Down
12 changes: 6 additions & 6 deletions src/lib/airGap.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { TxBuilderHelper } from '@aeternity/aepp-sdk';
import { decode, encode } from 'rlp';
import { decode, encode, Encoding } from '@aeternity/aepp-sdk-next';
import { decode as rlpDecode, encode as rlpEncode } from 'rlp';

function encodeBase58Check(data) {
return TxBuilderHelper.encode(data, 'cm').slice(3);
return encode(data, Encoding.Commitment).slice(3);
}

function decodeBase58Check(encodedData) {
return TxBuilderHelper.decode(`cm_${encodedData}`, 'cm');
return decode(`${Encoding.Commitment}_${encodedData}`, Encoding.Commitment);
}

const AIR_GAP_VERSION = '2';
Expand All @@ -17,7 +17,7 @@ const AIR_GAP_CALLBACK = 'https://base.aepps.com/airgap?d=';
const urlToPayload = (urlBroken, expectedMessageType) => {
// TODO: Remove after releasing https://github.com/airgap-it/airgap-vault/pull/64
const url = urlBroken.replace('airgap-wallet://?d=com/airgap?d=', AIR_GAP_CALLBACK);
const raw = decode(decodeBase58Check(new URL(url).searchParams.get('d')));
const raw = rlpDecode(decodeBase58Check(new URL(url).searchParams.get('d')));
const version = raw[0].toString();
if (version !== AIR_GAP_VERSION) throw new Error(`Unsupported AirGap protocol version: ${version}`);
const type = raw[1].toString();
Expand Down Expand Up @@ -69,7 +69,7 @@ export const generateSignRequestUrl = (networkId, transaction, publicKey) => {
];

const url = new URL('airgap-vault://');
url.searchParams.set('d', encodeBase58Check(encode(rlp)));
url.searchParams.set('d', encodeBase58Check(rlpEncode(rlp)));
return url.toString();
};

Expand Down
27 changes: 18 additions & 9 deletions src/lib/spendTxFees.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,26 @@
import BigNumber from 'bignumber.js';
import { TxBuilder } from '@aeternity/aepp-sdk';
import { buildTx, unpackTx, Tag } from '@aeternity/aepp-sdk-next';
import { MAGNITUDE, MAGNITUDE_MICRO } from './constants';

const STUB_ADDRESS = 'ak_enAPooFqpTQKkhJmU47J16QZu9HbPQQPwWBVeGnzDbDnv9dxp';

export const calculateMinSpendTxFee = (options) => (
unpackTx(
buildTx({
...options,
tag: Tag.SpendTx,
senderId: STUB_ADDRESS,
recipientId: STUB_ADDRESS,
}),
Tag.SpendTx,
).fee
);

const MAX_UINT256 = BigNumber(2).exponentiatedBy(256).minus(1);
const MIN_SPEND_TX_FEE_STRING = TxBuilder.calculateMinFee('spendTx', {
params: {
senderId: STUB_ADDRESS,
recipientId: STUB_ADDRESS,
amount: MAX_UINT256,
ttl: MAX_UINT256,
nonce: MAX_UINT256,
},
const MIN_SPEND_TX_FEE_STRING = calculateMinSpendTxFee({
amount: MAX_UINT256,
ttl: MAX_UINT256,
nonce: MAX_UINT256,
});

export const MIN_SPEND_TX_FEE = BigNumber(MIN_SPEND_TX_FEE_STRING).shiftedBy(-MAGNITUDE);
Expand Down
25 changes: 8 additions & 17 deletions src/pages/SendAmountMixin.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { pick } from 'lodash-es';
import BigNumber from 'bignumber.js';
import { TxBuilder } from '@aeternity/aepp-sdk';
import { MAGNITUDE } from '../lib/constants';
import { calculateMinSpendTxFee } from '../lib/spendTxFees';

export default {
data: () => ({
Expand Down Expand Up @@ -32,22 +32,13 @@ export default {
},
mounted() {
this.$watch(
({ activeAccount: { address, nonce }, amount }) => ({ address, nonce, amount }),
async ({ address, nonce, amount }) => {
const sdk = this.$store.state.sdk.then
? await this.$store.state.sdk : this.$store.state.sdk;
const minFee = BigNumber(TxBuilder.calculateMinFee('spendTx', {
gas: sdk.Ae.defaults.gas,
params: {
...sdk.Ae.defaults,
senderId: address,
recipientId: address,
amount: BigNumber(amount > 0 ? amount : 0).shiftedBy(MAGNITUDE),
ttl: 0,
nonce: nonce + 1,
payload: '',
},
})).shiftedBy(-MAGNITUDE);
({ activeAccount: { nonce }, amount }) => ({ nonce, amount }),
async ({ nonce, amount }) => {
const minFeeString = calculateMinSpendTxFee({
amount: BigNumber(amount > 0 ? amount : 0).shiftedBy(MAGNITUDE),
nonce: nonce + 1,
});
const minFee = BigNumber(minFeeString).shiftedBy(-MAGNITUDE);
if (!minFee.isEqualTo(this.minFee)) this.minFee = minFee;
},
{ immediate: true },
Expand Down
28 changes: 11 additions & 17 deletions src/pages/mobile/RedeemBalance.vue
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,7 @@
<script>
import { pick } from 'lodash-es';
import BigNumber from 'bignumber.js';
import {
Ae, Transaction, Crypto, TxBuilderHelper,
} from '@aeternity/aepp-sdk';
import { MemoryAccount, Node, transferFunds } from '@aeternity/aepp-sdk-next';
import { handleUnknownError } from '../../lib/utils';
import AeSpinner from '../../components/AeSpinner.vue';
import Page from '../../components/Page.vue';
Expand All @@ -60,15 +58,15 @@ export default {
LeftMore,
},
data: () => ({
keypair: null,
inviteAccount: null,
balance: 0,
busy: true,
}),
subscriptions() {
return pick(this.$store.state.observables, ['accounts']);
},
async mounted() {
while (!this.keypair) {
while (!this.inviteAccount) {
try {
await this.readQrCode(); // eslint-disable-line no-await-in-loop
} catch (error) {
Expand Down Expand Up @@ -102,8 +100,9 @@ export default {
return;
}

const address = TxBuilderHelper.encode(Crypto.generateKeyPairFromSecret(privateKey).publicKey, 'ak');
this.balance = BigNumber(await this.$store.state.sdk.getBalance(address))
const account = new MemoryAccount(privateKey);
const sdk = this.$store.state.sdk.then ? await this.$store.state.sdk : this.$store.state.sdk;
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 @@ -113,19 +112,14 @@ export default {
return;
}

this.keypair = { address, privateKey };
this.inviteAccount = account;
},
async sendToAccount(accountTo) {
this.busy = true;
const { hash, tx: { amount } } = await (
await Ae.compose(Transaction, {
methods: {
sign: (data) => Promise.resolve(Crypto.sign(data, this.keypair.privateKey)),
address: () => Promise.resolve(this.keypair.address),
},
})({ url: this.$store.state.sdkUrl })
)
.transferFunds(1, accountTo);
const { hash, tx: { amount } } = await transferFunds(1, accountTo, {
onAccount: this.inviteAccount,
onNode: new Node(this.$store.state.sdkUrl),
});
this.$router.push({ name: 'transfer' });
this.$store.dispatch('modals/open', {
name: 'spendSuccess',
Expand Down
4 changes: 2 additions & 2 deletions src/store/modules/accounts/airGap.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/* eslint no-param-reassign: ['error', { 'ignorePropertyModificationsFor': ['state'] }] */

import { TxBuilderHelper } from '@aeternity/aepp-sdk';
import { encode, Encoding } from '@aeternity/aepp-sdk-next';
import { getDesktopRemoteSignAction } from './utils';
import {
getPublicKeyByResponseUrl, getSignedTransactionByResponseUrl, generateSignRequestUrl,
Expand Down Expand Up @@ -34,7 +34,7 @@ export default {
actions: ENV_MOBILE_DEVICE ? {
createByResponseUrl({ commit }, { responseUrl, transport = TRANSPORT_DEEP_LINK }) {
const publicKey = getPublicKeyByResponseUrl(responseUrl);
const address = TxBuilderHelper.encode(publicKey, 'ak');
const address = encode(publicKey, Encoding.AccountAddress);
commit('accounts/add', {
address,
active: true,
Expand Down
3 changes: 2 additions & 1 deletion src/store/modules/accounts/hdWallet.js
Original file line number Diff line number Diff line change
Expand Up @@ -285,7 +285,8 @@ export default {
return dispatch('signWithoutConfirmation', data);
},

async signTransaction({ dispatch, rootState: { sdk } }, txBase64) {
async signTransaction({ dispatch, rootState }, txBase64) {
const sdk = rootState.sdk.then ? await rootState.sdk : rootState.sdk;
const encodedTx = await dispatch('confirmTxSigning', txBase64);
const signature = await dispatch(
'signWithoutConfirmation',
Expand Down
21 changes: 7 additions & 14 deletions src/store/modules/accounts/ledger.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import TransportWebUSB from '@ledgerhq/hw-transport-webusb';
import Ae from '@aeternity/ledger-app-api';
import { TxBuilder, SCHEMA } from '@aeternity/aepp-sdk';
import { buildTx, decode, Tag } from '@aeternity/aepp-sdk-next';
import { i18n } from '../../plugins/ui/languages';
import { RUNNING_IN_FRAME } from '../../../lib/constants';

Expand Down Expand Up @@ -95,26 +95,19 @@ export default {

sign: () => Promise.reject(new Error('Not implemented yet')),

async signTransaction({ rootGetters, dispatch, rootState: { sdk } }, txBase64) {
async signTransaction({ rootGetters, dispatch, rootState: { sdk } }, encodedTx) {
await dispatch('ensureCurrentAccountAvailable');

const txObject = TxBuilder.unpackTx(txBase64).tx;
const binaryTx = TxBuilder.buildTx(
txObject,
SCHEMA.OBJECT_ID_TX_TYPE[txObject.tag],
{ vsn: txObject.VSN },
).rlpEncoded;

const signature = Buffer.from(await dispatch('request', {
const signatureHex = await dispatch('request', {
name: 'signTransaction',
args: [
rootGetters['accounts/active'].source.idx,
binaryTx,
decode(encodedTx),
sdk.getNetworkId(),
],
}), 'hex');
return TxBuilder
.buildTx({ encodedTx: binaryTx, signatures: [signature] }, SCHEMA.TX_TYPE.signed).tx;
});
const signature = Buffer.from(signatureHex, 'hex');
return buildTx({ tag: Tag.SignedTx, encodedTx, signatures: [signature] });
},
},
};
2 changes: 1 addition & 1 deletion src/store/plugins/ui/currencies.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ const currencies = {
},
};

export default async (store) => {
export default (store) => {
const preferredCurrencyCode = 'eur';

store.registerModule('currencies', {
Expand Down
Loading
Loading