Skip to content

Commit

Permalink
refactor(tx-builder): make EncodedData based on enum
Browse files Browse the repository at this point in the history
  • Loading branch information
davidyuk committed Jul 26, 2022
1 parent 5ec9e56 commit 0773e14
Show file tree
Hide file tree
Showing 49 changed files with 675 additions and 482 deletions.
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
18 changes: 11 additions & 7 deletions src/AeSdkBase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,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 @@ -190,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 @@ -206,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 @@ -263,7 +263,7 @@ class AeSdkBase {
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 @@ -296,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
8 changes: 4 additions & 4 deletions src/account/Base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
*/
import { messageToHash, verifyMessage as verifyMessageCrypto, hash } from '../utils/crypto';
import { buildTx } from '../tx/builder';
import { decode, EncodedData } from '../utils/encoder';
import { decode, Encoded } from '../utils/encoder';
import { Tag } from '../tx/builder/constants';
import { getNetworkId } from '../Node';
import { concatBuffers } from '../utils/other';
Expand Down Expand Up @@ -53,14 +53,14 @@ 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);
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>;
}
13 changes: 7 additions & 6 deletions src/account/Memory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,13 @@ import AccountBase from './Base';
import { sign, isValidKeypair } from '../utils/crypto';
import { isHex } from '../utils/string';
import { ArgumentError, InvalidKeypairError, MissingParamError } from '../utils/errors';
import { decode, 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 @@ -42,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 @@ -78,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 @@ -91,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
14 changes: 7 additions & 7 deletions src/aens.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ import {
CLIENT_TTL, NAME_TTL, Tag, AensName,
} from './tx/builder/constants';
import { ArgumentError } from './utils/errors';
import { EncodedData } from './utils/encoder';
import { Encoded } from './utils/encoder';
import { send, SendOptions } from './spend';
import { getName, getHeight } from './chain';
import { _buildTx, BuildTxOptions } from './tx';
Expand Down Expand Up @@ -166,7 +166,7 @@ interface AensUpdateOptions extends
*/
export async function aensTransfer(
name: AensName,
account: EncodedData<'ak'>,
account: Encoded.AccountAddress,
options: AensTransferOptions,
): ReturnType<typeof send> {
const nameTransferTx = await _buildTx(Tag.NameTransferTx, {
Expand Down Expand Up @@ -210,8 +210,8 @@ export async function aensQuery(
& Parameters<typeof aensTransfer>[2],
): Promise<Readonly<
TransformNodeType<NameEntry> & {
id: EncodedData<'nm'>;
owner: EncodedData<'ak'>;
id: Encoded.Name;
owner: Encoded.AccountAddress;
pointers: KeyPointers | NamePointer[];
ttl: number;
update: (
Expand All @@ -221,7 +221,7 @@ export async function aensQuery(
}
) => ReturnType<typeof aensUpdate> & ReturnType<typeof aensQuery>;
transfer: (
account: EncodedData<'ak'>,
account: Encoded.AccountAddress,
options?: Parameters<typeof aensQuery>[1]
) => ReturnType<typeof aensUpdate> & ReturnType<typeof aensQuery>;
revoke: (options?: Omit<Parameters<typeof aensRevoke>[1], 'onNode' | 'onCompiler' | 'onAccount'> & {
Expand All @@ -237,8 +237,8 @@ export async function aensQuery(
const nameEntry = await getName(name, opt);
return Object.freeze({
...nameEntry,
id: nameEntry.id as EncodedData<'nm'>,
owner: nameEntry.owner as EncodedData<'ak'>,
id: nameEntry.id as Encoded.Name,
owner: nameEntry.owner as Encoded.AccountAddress,
async update(pointers, options) {
return {
...await aensUpdate(name, pointers, { ...opt, ...options }),
Expand Down
Loading

0 comments on commit 0773e14

Please sign in to comment.