Skip to content

Commit

Permalink
Merge pull request #1622 from aeternity/feature/serialization
Browse files Browse the repository at this point in the history
Sync with aeserialization
  • Loading branch information
davidyuk authored Jul 26, 2022
2 parents 34c4a59 + 2b25e5d commit 7be2615
Show file tree
Hide file tree
Showing 57 changed files with 1,160 additions and 862 deletions.
2 changes: 1 addition & 1 deletion docs/guides/low-vs-high-usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ async function spend (amount, recipient) {
)

// builds an unsigned SpendTx using the debug endpoint of the node's API
const spendTx = await aeSdk.buildTx(TX_TYPE.spend, {
const spendTx = await aeSdk.buildTx(Tag.SpendTx, {
senderId: await aeSdk.address(),
recipientId: recipient,
fee: 18000000000000, // you must provide enough fee
Expand Down
4 changes: 2 additions & 2 deletions examples/node/paying-for-tx-contract-call-tx.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@
// You need to import `AeSdk`, `Node` and `MemoryAccount` classes from the SDK.
// Additionally you import the `generateKeyPair` utility function to generate a new keypair.
const {
AeSdk, Node, MemoryAccount, generateKeyPair, TX_TYPE,
AeSdk, Node, MemoryAccount, generateKeyPair, Tag,
} = require('@aeternity/aepp-sdk');

// **Note**:
Expand Down Expand Up @@ -131,7 +131,7 @@ const NEW_USER_KEYPAIR = generateKeyPair();
{ source: CONTRACT_SOURCE, contractAddress: CONTRACT_ADDRESS },
);
const calldata = contract.calldata.encode('PayingForTxExample', 'set_last_caller', []);
const contractCallTx = await aeSdk.buildTx(TX_TYPE.contractCall, {
const contractCallTx = await aeSdk.buildTx(Tag.ContractCallTx, {
callerId: await newUserAccount.address(),
contractId: CONTRACT_ADDRESS,
amount: 0,
Expand Down
4 changes: 2 additions & 2 deletions examples/node/paying-for-tx-spend-tx.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
// You need to import `AeSdk`, `Node` and `MemoryAccount` classes from the SDK.
// Additionally you import the `generateKeyPair` utility function to generate a new keypair.
const {
AeSdk, Node, MemoryAccount, generateKeyPair, TX_TYPE,
AeSdk, Node, MemoryAccount, generateKeyPair, Tag,
} = require('@aeternity/aepp-sdk');

// **Note**:
Expand Down Expand Up @@ -91,7 +91,7 @@ const AMOUNT = 1;
// - The balance should now be 1

// ## 7. Create and sign `SpendTx` on behalf of new user
const spendTx = await aeSdk.buildTx(TX_TYPE.spend, {
const spendTx = await aeSdk.buildTx(Tag.SpendTx, {
senderId: await newUserAccount.address(),
recipientId: await payerAccount.address(),
amount: AMOUNT,
Expand Down
20 changes: 11 additions & 9 deletions src/AeSdk.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
import AeSdkBase, { Account } from './AeSdkBase';
import AccountBase from './account/Base';
import { decode, EncodedData } from './utils/encoder';
import { decode, Encoded } from './utils/encoder';
import { UnavailableAccountError } from './utils/errors';

export default class AeSdk extends AeSdkBase {
accounts: { [key: EncodedData<'ak'>]: AccountBase } = {};
accounts: { [key: Encoded.AccountAddress]: AccountBase } = {};

selectedAddress?: EncodedData<'ak'>;
selectedAddress?: Encoded.AccountAddress;

_resolveAccount(account: Account | EncodedData<'ak'> = this.selectedAddress): AccountBase {
_resolveAccount(
account: Account | Encoded.AccountAddress = this.selectedAddress,
): AccountBase {
if (typeof account === 'string') {
const address = account as EncodedData<'ak'>;
const address = account as Encoded.AccountAddress;
decode(address);
if (this.accounts[address] == null) throw new UnavailableAccountError(account);
account = this.accounts[address];
Expand All @@ -22,8 +24,8 @@ export default class AeSdk extends AeSdkBase {
* Get accounts addresses
* @example addresses()
*/
addresses(): Array<EncodedData<'ak'>> {
return Object.keys(this.accounts) as Array<EncodedData<'ak'>>;
addresses(): Encoded.AccountAddress[] {
return Object.keys(this.accounts) as Encoded.AccountAddress[];
}

/**
Expand All @@ -44,7 +46,7 @@ export default class AeSdk extends AeSdkBase {
* @param address - Address of account to remove
* @example removeAccount(address)
*/
removeAccount(address: EncodedData<'ak'>): void {
removeAccount(address: Encoded.AccountAddress): void {
if (this.accounts[address] == null) {
console.warn(`removeAccount: Account for ${address} not available`);
return;
Expand All @@ -58,7 +60,7 @@ export default class AeSdk extends AeSdkBase {
* @param address - Address of account to select
* @example selectAccount('ak_xxxxxxxx')
*/
selectAccount(address: EncodedData<'ak'>): void {
selectAccount(address: Encoded.AccountAddress): void {
decode(address);
if (this.accounts[address] == null) throw new UnavailableAccountError(address);
this.selectedAddress = address;
Expand Down
10 changes: 5 additions & 5 deletions src/AeSdkAepp.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import AeSdkBase, { Account } from './AeSdkBase';
import AccountBase from './account/Base';
import AccountRpc from './account/Rpc';
import { decode, EncodedData } from './utils/encoder';
import { decode, Encoded } from './utils/encoder';
import {
Accounts, RPC_VERSION, WalletInfo, Network, WalletApi, AeppApi,
} from './aepp-wallet-communication/rpc/types';
Expand Down Expand Up @@ -63,7 +63,7 @@ export default class AeSdkAepp extends AeSdkBase {

_resolveAccount(account: Account = this.addresses()[0]): AccountBase {
if (typeof account === 'string') {
const address = account as EncodedData<'ak'>;
const address = account as Encoded.AccountAddress;
decode(address);
if (!this.addresses().includes(address)) throw new UnAuthorizedAccountError(address);
account = new AccountRpc({ rpcClient: this.rpcClient, address });
Expand All @@ -72,12 +72,12 @@ export default class AeSdkAepp extends AeSdkBase {
return super._resolveAccount(account);
}

addresses(): Array<EncodedData<'ak'>> {
addresses(): Encoded.AccountAddress[] {
if (this._accounts == null) return [];
const current = Object.keys(this._accounts.current)[0];
return [
...current != null ? [current] : [], ...Object.keys(this._accounts.connected),
] as Array<EncodedData<'ak'>>;
] as Encoded.AccountAddress[];
}

/**
Expand Down Expand Up @@ -142,7 +142,7 @@ export default class AeSdkAepp extends AeSdkBase {
* Ask addresses from wallet
* @returns Addresses from wallet
*/
async askAddresses(): Promise<Array<EncodedData<'ak'>>> {
async askAddresses(): Promise<Encoded.AccountAddress[]> {
this._ensureAccountAccess();
return this.rpcClient.request(METHODS.address, undefined);
}
Expand Down
23 changes: 14 additions & 9 deletions src/AeSdkBase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ import { _buildTx } from './tx';
import { mapObject } from './utils/other';
import Node, { getNetworkId } from './Node';
import { AE_AMOUNT_FORMATS } from './utils/amount-formatter';
import { AMOUNT, TX_TYPE } from './tx/builder/schema';
import { AMOUNT } from './tx/builder/schema';
import { Tag } from './tx/builder/constants';
import MemoryAccount, { Keypair } from './account/Memory';
import AccountBase, { isAccountBase } from './account/Base';
import {
Expand All @@ -20,7 +21,7 @@ import {
NotImplementedError,
TypeError,
} from './utils/errors';
import { EncodedData } from './utils/encoder';
import { Encoded } from './utils/encoder';
import Compiler from './contract/Compiler';

export type Account = Keypair | AccountBase | any;
Expand Down Expand Up @@ -189,11 +190,11 @@ class AeSdkBase {
}

// eslint-disable-next-line class-methods-use-this
addresses(): Array<EncodedData<'ak'>> {
addresses(): Encoded.AccountAddress[] {
return [];
}

async address({ onAccount }: { onAccount?: Account } = {}): Promise<EncodedData<'ak'>> {
async address({ onAccount }: { onAccount?: Account } = {}): Promise<Encoded.AccountAddress> {
return this._resolveAccount(onAccount).address();
}

Expand All @@ -205,9 +206,9 @@ class AeSdkBase {
}

async signTransaction(
tx: EncodedData<'tx'>,
tx: Encoded.Transaction,
{ onAccount, ...options }: { onAccount?: Account } & Parameters<AccountBase['signTransaction']>[1] = {},
): Promise<EncodedData<'tx'>> {
): Promise<Encoded.Transaction> {
return this._resolveAccount(onAccount)
.signTransaction(tx, { ...options, networkId: await this.getNetworkId(options) });
}
Expand Down Expand Up @@ -259,10 +260,10 @@ class AeSdkBase {
};
}

async buildTx<TxType extends TX_TYPE>(
async buildTx<TxType extends Tag>(
txType: TxType,
options: Omit<Parameters<typeof _buildTx<TxType>>[1], 'onNode'> & { onNode?: Node },
): Promise<EncodedData<'tx'>> {
): Promise<Encoded.Transaction> {
// @ts-expect-error TODO: need to figure out what's wrong here
return _buildTx<TxType>(txType, {
...this._getOptions(),
Expand Down Expand Up @@ -295,7 +296,11 @@ type MakeOptional<Args extends any[]> = Args extends [infer Head, ...infer Tail]
? Tail extends []
? Head extends object
? OptionalIfNotRequired<[Omit<Head, 'onNode' | 'onCompiler' | 'onAccount'>
& { onNode?: Node; onCompiler?: Compiler; onAccount?: AccountBase | EncodedData<'ak'> | Keypair }]>
& {
onNode?: Node;
onCompiler?: Compiler;
onAccount?: AccountBase | Encoded.AccountAddress | Keypair;
}]>
: [Head]
: [Head, ...MakeOptional<Tail>]
: never;
Expand Down
6 changes: 3 additions & 3 deletions src/AeSdkWallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import {
WalletApi,
WalletInfo,
} from './aepp-wallet-communication/rpc/types';
import { EncodedData } from './utils/encoder';
import { Encoded } from './utils/encoder';
import jsonBig from './utils/json-big';

type RpcClientWallet = RpcClient<AeppApi, WalletApi>;
Expand All @@ -34,7 +34,7 @@ type OnSubscription = (

type OnSign = (
clientId: string, params: Parameters<WalletApi[METHODS.sign]>[0], origin: string
) => Promise<{ tx?: EncodedData<'tx'>; onAccount?: Account } | undefined> | Promise<void>;
) => Promise<{ tx?: Encoded.Transaction; onAccount?: Account } | undefined> | Promise<void>;

type OnDisconnect = (
clientId: string, params: Parameters<WalletApi[METHODS.closeConnection]>[0]
Expand Down Expand Up @@ -135,7 +135,7 @@ export default class AeSdkWallet extends AeSdk {
.forEach((client) => client.notify(METHODS.updateAddress, this.getAccounts()));
}

selectAccount(address: EncodedData<'ak'>): void {
selectAccount(address: Encoded.AccountAddress): void {
super.selectAccount(address);
this._pushAccountsToApps();
}
Expand Down
4 changes: 2 additions & 2 deletions src/Node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {
} from './utils/autorest';
import { Node as NodeApi, NodeOptionalParams, ErrorModel } from './apis/node';
import { mapObject } from './utils/other';
import { EncodedData } from './utils/encoder';
import { Encoded } from './utils/encoder';
import { MissingParamError } from './utils/errors';

/**
Expand Down Expand Up @@ -53,7 +53,7 @@ export type TransformNodeType<Type> =
: Property extends NumberPropertyNames
? PreserveOptional<number, Type[Property]>
: Property extends 'txHash'
? PreserveOptional<EncodedData<'th'>, Type[Property]>
? PreserveOptional<Encoded.TxHash, Type[Property]>
: TransformNodeType<Type[Property]>
}
: Type;
Expand Down
12 changes: 6 additions & 6 deletions src/account/Base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@
*/
import { messageToHash, verifyMessage as verifyMessageCrypto, hash } from '../utils/crypto';
import { buildTx } from '../tx/builder';
import { decode, EncodedData } from '../utils/encoder';
import { TX_TYPE } from '../tx/builder/schema';
import { decode, Encoded } from '../utils/encoder';
import { Tag } from '../tx/builder/constants';
import { getNetworkId } from '../Node';
import { concatBuffers } from '../utils/other';
import type { createMetaTx } from '../contract/ga';
Expand Down Expand Up @@ -53,21 +53,21 @@ export default abstract class AccountBase {
* @returns Signed transaction
*/
async signTransaction(
tx: EncodedData<'tx'>,
tx: Encoded.Transaction,
{ innerTx, networkId, ...options }: {
innerTx?: boolean;
networkId?: string;
authData?: Parameters<typeof createMetaTx>[1];
authFun?: Parameters<typeof createMetaTx>[2];
} & Omit<Partial<Parameters<typeof createMetaTx>[3]>, 'onAccount'> = {},
): Promise<EncodedData<'tx'>> {
): Promise<Encoded.Transaction> {
const prefixes = [await this.getNetworkId({ networkId })];
if (innerTx === true) prefixes.push('inner_tx');
const rlpBinaryTx = decode(tx);
const txWithNetworkId = concatBuffers([Buffer.from(prefixes.join('-')), hash(rlpBinaryTx)]);

const signatures = [await this.sign(txWithNetworkId, options)];
return buildTx({ encodedTx: rlpBinaryTx, signatures }, TX_TYPE.signed).tx;
return buildTx({ encodedTx: rlpBinaryTx, signatures }, Tag.SignedTx).tx;
}

/**
Expand Down Expand Up @@ -120,5 +120,5 @@ export default abstract class AccountBase {
* Obtain account address
* @returns Public account address
*/
abstract address(opt?: object): Promise<EncodedData<'ak'>>;
abstract address(opt?: object): Promise<Encoded.AccountAddress>;
}
14 changes: 7 additions & 7 deletions src/account/Memory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,14 @@
import AccountBase from './Base';
import { sign, isValidKeypair } from '../utils/crypto';
import { isHex } from '../utils/string';
import { decode } from '../tx/builder/helpers';
import { ArgumentError, InvalidKeypairError, MissingParamError } from '../utils/errors';
import { EncodedData } from '../utils/encoder';
import { decode, Encoded } from '../utils/encoder';
import { createMetaTx } from '../contract/ga';

const secrets = new WeakMap();

export interface Keypair {
publicKey: EncodedData<'ak'>;
publicKey: Encoded.AccountAddress;
secretKey: string | Uint8Array;
}

Expand All @@ -43,7 +42,8 @@ export default class AccountMemory extends AccountBase {
* @param options.gaId - Address of generalized account
*/
constructor(
{ keypair, gaId, ...options }: { keypair?: Keypair; gaId?: EncodedData<'ak'> } & ConstructorParameters<typeof AccountBase>[0],
{ keypair, gaId, ...options }: { keypair?: Keypair; gaId?: Encoded.AccountAddress }
& ConstructorParameters<typeof AccountBase>[0],
) {
super(options);

Expand Down Expand Up @@ -79,9 +79,9 @@ export default class AccountMemory extends AccountBase {
}

async signTransaction(
tx: EncodedData<'tx'>,
tx: Encoded.Transaction,
options: Parameters<AccountBase['signTransaction']>[1] = {},
): Promise<EncodedData<'tx'>> {
): Promise<Encoded.Transaction> {
if (!this.isGa || options.innerTx === true) return super.signTransaction(tx, options);
const {
authData, authFun, onCompiler, onNode,
Expand All @@ -92,7 +92,7 @@ export default class AccountMemory extends AccountBase {
return createMetaTx(tx, authData, authFun, { onCompiler, onNode, onAccount: this });
}

async address(): Promise<EncodedData<'ak'>> {
async address(): Promise<Encoded.AccountAddress> {
return secrets.get(this).publicKey;
}
}
14 changes: 7 additions & 7 deletions src/account/Rpc.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import AccountBase from './Base';
import { METHODS } from '../aepp-wallet-communication/schema';
import { NotImplementedError } from '../utils/errors';
import { EncodedData } from '../utils/encoder';
import { Encoded } from '../utils/encoder';

/**
* Account provided by wallet
Expand All @@ -13,11 +13,11 @@ import { EncodedData } from '../utils/encoder';
export default class AccountRpc extends AccountBase {
_rpcClient: any;

_address: EncodedData<'ak'>;
_address: Encoded.AccountAddress;

constructor(
{ rpcClient, address, ...options }:
{ rpcClient: any; address: EncodedData<'ak'> } & ConstructorParameters<typeof AccountBase>[0],
{ rpcClient, address, ...options }: { rpcClient: any; address: Encoded.AccountAddress }
& ConstructorParameters<typeof AccountBase>[0],
) {
super(options);
this._rpcClient = rpcClient;
Expand All @@ -29,17 +29,17 @@ export default class AccountRpc extends AccountBase {
throw new NotImplementedError('RAW signing using wallet');
}

async address(): Promise<EncodedData<'ak'>> {
async address(): Promise<Encoded.AccountAddress> {
return this._address;
}

/**
* @returns Signed transaction
*/
async signTransaction(
tx: EncodedData<'tx'>,
tx: Encoded.Transaction,
{ innerTx, networkId }: Parameters<AccountBase['signTransaction']>[1] = {},
): Promise<EncodedData<'tx'>> {
): Promise<Encoded.Transaction> {
if (innerTx != null) throw new NotImplementedError('innerTx option in AccountRpc');
const res = await this._rpcClient.request(METHODS.sign, {
onAccount: this._address,
Expand Down
Loading

0 comments on commit 7be2615

Please sign in to comment.