Skip to content

Commit

Permalink
refactor(tests)!: migrate remaining tests ts
Browse files Browse the repository at this point in the history
BREAKING CHANGE: `computeBidFee` accepts `startFee`, `increment` as options
  • Loading branch information
martinkaintas authored and davidyuk committed Jun 16, 2022
1 parent 88d25af commit 3fc6f6d
Show file tree
Hide file tree
Showing 24 changed files with 313 additions and 216 deletions.
11 changes: 6 additions & 5 deletions src/AeSdkBase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,10 +53,11 @@ function getValueOrErrorProxy<Value extends object> (valueCb: () => Value): Valu
* available.
*/
class AeSdkBase {
_options = {
denomination: AE_AMOUNT_FORMATS.AETTOS,
amount: AMOUNT
}
_options: {
denomination: AE_AMOUNT_FORMATS
amount: number
[key: string]: any
} = { denomination: AE_AMOUNT_FORMATS.AETTOS, amount: AMOUNT }

pool: Map<string, Node> = new Map()
selectedNodeName?: string
Expand Down Expand Up @@ -190,7 +191,7 @@ class AeSdkBase {
}

async sign (
data: string, { onAccount, ...options }: { onAccount?: Account } = {}
data: string | Uint8Array, { onAccount, ...options }: { onAccount?: Account } = {}
): Promise<Uint8Array> {
return await this._resolveAccount(onAccount).sign(data, options)
}
Expand Down
2 changes: 1 addition & 1 deletion src/account/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ export default abstract class AccountBase {
* @param options - Options
* @returns Signed data blob
*/
abstract sign (data: string | Buffer, options?: any): Promise<Uint8Array>
abstract sign (data: string | Uint8Array, options?: any): Promise<Uint8Array>

/**
* Obtain account address
Expand Down
2 changes: 1 addition & 1 deletion src/account/memory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ export default class AccountMemory extends AccountBase {
})
}

async sign (data: string): Promise<Uint8Array> {
async sign (data: string | Uint8Array): Promise<Uint8Array> {
if (this.isGa) throw new InvalidKeypairError('You are trying to sign data using generalized account without keypair')
return sign(data, secrets.get(this).secretKey)
}
Expand Down
2 changes: 1 addition & 1 deletion src/account/rpc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export default class AccountRpc extends AccountBase {
this._address = address
}

async sign (data: string | Buffer, options?: any): Promise<Uint8Array> {
async sign (data: string | Uint8Array, options?: any): Promise<Uint8Array> {
throw new NotImplementedError('RAW signing using wallet')
}

Expand Down
24 changes: 15 additions & 9 deletions src/ae/aens.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ import { AensName, getName, height } from '../chain'
import { _buildTx, BuildTxOptions } from '../tx'
import { TransformNodeType } from '../node'
import { NameEntry } from '../apis/node'
import AccountBase from '../account/base'

interface KeyPointers {
[key: string]: string | Buffer
Expand Down Expand Up @@ -101,15 +102,15 @@ export async function aensRevoke (
*/
export async function aensUpdate (
name: AensName,
pointers: KeyPointers = {},
pointers: KeyPointers,
{ extendPointers, ...options }: { extendPointers?: boolean } & Parameters<typeof send>[1]
& BuildTxOptions<TX_TYPE.nameUpdate, 'nameId' | 'accountId' | 'pointers' | 'clientTtl' | 'nameTtl'>
& { clientTtl?: number, nameTtl?: number }
): ReturnType<typeof send> {
const allPointers = {
...extendPointers === true && Object.fromEntries(
(await getName(name, options)).pointers
.map(({ key, id }: {key: string, id: string}) => [key, id])
.map(({ key, id }: { key: string, id: string }) => [key, id])
),
...pointers
}
Expand Down Expand Up @@ -196,16 +197,21 @@ export async function aensQuery (
ttl: number
update: (
pointers: KeyPointers,
options: Parameters<typeof aensQuery>[1]
options?: Omit<Parameters<typeof aensQuery>[1], 'onNode' | 'onCompiler' | 'onAccount'> & {
onAccount?: AccountBase
}
) => ReturnType<typeof aensUpdate> & ReturnType<typeof aensQuery>
transfer: (
account: EncodedData<'ak'>,
options: Parameters<typeof aensQuery>[1]
options?: Parameters<typeof aensQuery>[1]
) => ReturnType<typeof aensUpdate> & ReturnType<typeof aensQuery>
revoke: (options: Parameters<typeof aensRevoke>[1]) => ReturnType<typeof aensRevoke>
revoke: (options?: Omit<Parameters<typeof aensRevoke>[1], 'onNode' | 'onCompiler' | 'onAccount'> & {
onAccount?: AccountBase
}
) => ReturnType<typeof aensRevoke>
extendTtl: (
nameTtl: number,
options: Parameters<typeof aensQuery>[1]
options?: Omit<Parameters<typeof aensQuery>[1], 'onNode' | 'onCompiler' | 'onAccount'>
) => ReturnType<typeof aensUpdate> & ReturnType<typeof aensQuery>
}
>> {
Expand Down Expand Up @@ -318,7 +324,7 @@ export async function aensPreclaim (
height: number
salt: number
commitmentId: string
claim: (opts: Parameters<typeof aensClaim>[2]) => ReturnType<typeof aensClaim>
claim: (opts?: Parameters<typeof aensClaim>[2]) => ReturnType<typeof aensClaim>
}
>> {
const _salt = salt()
Expand Down Expand Up @@ -363,8 +369,8 @@ export async function aensPreclaim (
*/
export async function aensBid (
name: AensName,
nameFee: BigNumber,
options: Omit<Parameters<typeof aensClaim>[2], 'nameFee' | 'VSN'>
nameFee: number | string | BigNumber,
options: Omit<Parameters<typeof aensClaim>[2], 'nameFee'>
): ReturnType<typeof aensClaim> {
return await aensClaim(name, 0, { ...options, nameFee })
}
6 changes: 3 additions & 3 deletions src/ae/oracle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ export async function getOracleObject (
id: EncodedData<'ok'>
queries: OracleQueries
// TODO: replace getOracleObject with a class
pollQueries: Function
pollQueries: (cb: Parameters<typeof pollForQueries>[1]) => ReturnType<typeof pollForQueries>
postQuery: Function
respondToQuery: Function
extendOracle: Function
Expand Down Expand Up @@ -141,9 +141,9 @@ export async function getQueryObject (
Awaited<ReturnType<Node['getOracleQueryByPubkeyAndQueryId']>> & {
decodedQuery: string
decodedResponse: string
respond: (response: string, options: Parameters<typeof respondToQuery>[3]) =>
respond: (response: string, options?: Parameters<typeof respondToQuery>[3]) =>
ReturnType<typeof respondToQuery>
pollForResponse: (options: Parameters<typeof pollForQueryResponse>[2]) =>
pollForResponse: (options?: Parameters<typeof pollForQueryResponse>[2]) =>
ReturnType<typeof pollForQueryResponse>
}
> {
Expand Down
12 changes: 4 additions & 8 deletions src/chain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,11 +79,7 @@ export async function sendTransaction (
if (validation.length > 0) {
const message = 'Transaction verification errors: ' +
validation.map((v: { message: string }) => v.message).join(', ')
throw Object.assign(new InvalidTxError(message), {
code: 'TX_VERIFICATION_ERROR',
validation,
transaction: tx
})
throw new InvalidTxError(message, validation, tx)
}
}

Expand Down Expand Up @@ -157,7 +153,7 @@ export async function waitForTxConfirm (
* @param options.onNode - Node to use
*/
export async function getAccount (
address: EncodedData<'ak'>,
address: EncodedData<'ak' | 'ct'>,
{ height, hash, onNode }:
{ height?: number, hash?: EncodedData<'kh' | 'mh'>, onNode: Node }
): Promise<TransformNodeType<AccountNode>> {
Expand All @@ -176,9 +172,9 @@ export async function getAccount (
* @param options.hash - The block hash on which to obtain the balance for (default: top of chain)
*/
export async function getBalance (
address: EncodedData<'ak'>,
address: EncodedData<'ak' | 'ct'>,
{ format = AE_AMOUNT_FORMATS.AETTOS, ...options }:
{ format: AE_AMOUNT_FORMATS } & Parameters<typeof getAccount>[1]
{ format?: AE_AMOUNT_FORMATS } & Parameters<typeof getAccount>[1]
): Promise<string> {
const { balance } = await getAccount(address, options).catch(() => ({ balance: 0n }))

Expand Down
49 changes: 35 additions & 14 deletions src/contract/aci.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ import { Aci as BaseAci } from '../apis/compiler'
import Compiler from './compiler'
import Node from '../node'
import {
getAccount, getContract, getContractByteCode, getKeyBlock, resolveName, txDryRun
getAccount, getContract, getContractByteCode, getKeyBlock, resolveName, txDryRun, AensName
} from '../chain'
import AccountBase from '../account/base'

Expand Down Expand Up @@ -113,10 +113,29 @@ export interface ContractInstance {
options: any
compile: (options?: {}) => Promise<EncodedData<'cb'>>
_estimateGas: (name: string, params: any[], options: object) => Promise<number>
deploy: (params: any[], options: object) => Promise<any>
call: (fn: string, params?: any[], options?: {}) => Promise<any>
decodeEvents: (events: Event[], { omitUnknown, ...opt }: {
omitUnknown?: boolean}) => DecodedEvent[]
deploy: (params?: any[], options?: object) => Promise<any>
call: (fn: string, params?: any[], options?: {}) => Promise<{
hash: string
tx: any
txData: TxData
rawTx: string
result: {
callerId: EncodedData<'ak'>
callerNonce: number
contractId: EncodedData<'ct'>
gasPrice: number
gasUsed: number
height: number
log: any[]
returnType: string
returnValue: string
}
decodedResult: any
decodedEvents: DecodedEvent[]
}>
decodeEvents: (
events: Event[], options?: { omitUnknown?: boolean, contractAddressToName?: any }
) => DecodedEvent[]
methods: any
}

Expand Down Expand Up @@ -158,9 +177,10 @@ export default async function getContractInstance ({
source?: string
bytecode?: EncodedData<'cb'>
aci?: Aci
contractAddress?: EncodedData<'ct'>
contractAddress?: EncodedData<'ct'> | AensName
fileSystem?: Record<string, string>
validateBytecode?: boolean
[key: string]: any
}): Promise<ContractInstance> {
if (_aci == null && source != null) {
// TODO: should be fixed when the compiledAci interface gets updated
Expand Down Expand Up @@ -200,13 +220,12 @@ export default async function getContractInstance ({
...otherOptions
},
compile: async function (_options?: {}): Promise<any> {},
_estimateGas: async function (_name: string, _params: any[], _options: object): Promise<any> {},
deploy: async function (_params: any[], _options: any): Promise<any> {},
_estimateGas: async function (
_name: string, _params: any[], _options: object
): Promise<any> {},
deploy: async function (_params?: any[], _options?: any): Promise<any> {},
call: async function (_fn: string, _params?: any[], _options?: {}): Promise<any> {},
decodeEvents (
_events: Event[],
{ omitUnknown, ...opt }: { omitUnknown?: boolean }
): any {},
decodeEvents (_events: Event[], options?: { omitUnknown?: boolean }): any {},
methods: undefined
}

Expand Down Expand Up @@ -259,7 +278,8 @@ export default async function getContractInstance ({
const handleCallError = (
{ returnType, returnValue }: {
returnType: ContractCallReturnType
returnValue: EncodedData<EncodingType>},
returnValue: EncodedData<EncodingType>
},
transaction: string): void => {
let message: string
switch (returnType) {
Expand Down Expand Up @@ -297,6 +317,7 @@ export default async function getContractInstance ({
): Promise<ContractInstance['deployInfo']> => {
const opt = { ...instance.options, ...options }
if (instance.bytecode == null) await instance.compile(opt)
// @ts-expect-error
if (opt.callStatic === true) return await instance.call('init', params, opt)
if (instance.deployInfo.address != null) throw new DuplicateContractError()

Expand Down Expand Up @@ -446,7 +467,7 @@ export default async function getContractInstance ({
*/
instance.decodeEvents = (
events: Event[],
{ omitUnknown, ...opt }: {omitUnknown?: boolean} = {}
{ omitUnknown, ...opt }: { omitUnknown?: boolean } = {}
): DecodedEvent[] => events
.map(event => {
const topics = event.topics.map((t: string | number) => BigInt(t))
Expand Down
4 changes: 2 additions & 2 deletions src/contract/ga.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,8 @@ export async function createGeneralizedAccount (
source: string,
args: any[],
{ onAccount, onCompiler, onNode, ...options }:
{ onAccount: AccountBase, onCompiler: Compiler, onNode: Node }
& BuildTxOptions<TX_TYPE.gaAttach, 'authFun' | 'callData' | 'code' | 'ownerId'>
{ onAccount: AccountBase, onCompiler: Compiler, onNode: Node, gasLimit?: number }
& BuildTxOptions<TX_TYPE.gaAttach, 'authFun' | 'callData' | 'code' | 'ownerId' | 'gasLimit'>
& Parameters<typeof send>[1]
): Promise<Readonly<{
owner: EncodedData<'ak'>
Expand Down
2 changes: 1 addition & 1 deletion src/tx/builder/field-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ export class NameFee extends Field {
* @param txFields - Transaction fields
* @param txFields.name - AENS Name in transaction
*/
static serialize (value: Int, { name }: { name: AensName }): Buffer {
static serialize (value: Int | undefined, { name }: { name: AensName }): Buffer {
const minNameFee = getMinimumNameFee(name)
value ??= minNameFee
if (minNameFee.gt(value)) {
Expand Down
10 changes: 6 additions & 4 deletions src/tx/builder/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -209,17 +209,19 @@ export function getMinimumNameFee (name: AensName): BigNumber {
* Compute bid fee for AENS auction
*
* @param name - the AENS name to get the fee for
* @param startFee - Auction start fee
* @param increment - Bid multiplier(In percentage, must be between 0 and 1)
* @param options - Options
* @param options.startFee - Auction start fee
* @param options.increment - Bid multiplier(In percentage, must be between 0 and 1)
* @returns Bid fee
*/
export function computeBidFee (
name: AensName,
startFee: number | string | null,
increment: number = NAME_FEE_BID_INCREMENT
{ startFee, increment = NAME_FEE_BID_INCREMENT }:
{ startFee?: number | string | BigNumber, increment?: number } = {}
): BigNumber {
if (!(Number(increment) === increment && increment % 1 !== 0)) throw new IllegalBidFeeError(`Increment must be float. Current increment ${increment}`)
if (increment < NAME_FEE_BID_INCREMENT) throw new IllegalBidFeeError(`minimum increment percentage is ${NAME_FEE_BID_INCREMENT}`)
// FIXME: increment should be used somehow here
return ceil(
new BigNumber(startFee ?? getMinimumNameFee(name))
.times(new BigNumber(NAME_FEE_BID_INCREMENT).plus(1))
Expand Down
20 changes: 15 additions & 5 deletions src/tx/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,16 @@ export type BuildTxOptions <TxType extends TX_TYPE, OmitFields extends string> =
// TODO: find a better name or rearrange methods
export async function _buildTx<TxType extends TX_TYPE> (
txType: TxType,
{ denomination, ..._params }:
{ denomination, absoluteTtl, ..._params }:
Omit<Parameters<typeof syncBuildTx<TxType, 'tx'>>[0], 'fee' | 'nonce' | 'ttl' | 'ctVersion' | 'abiVersion'>
& { onNode: Node, fee?: Int, nonce?: number, ttl?: number, denomination?: AE_AMOUNT_FORMATS }
& {
onNode: Node
fee?: Int
nonce?: number
ttl?: number
denomination?: AE_AMOUNT_FORMATS
absoluteTtl?: boolean
}
& (TxType extends TX_TYPE.oracleExtend | TX_TYPE.oracleResponse ? { callerId: EncodedData<'ak'> } : {})
& (TxType extends TX_TYPE.contractCreate | TX_TYPE.gaAttach ? { ctVersion?: CtVersion } : {})
& (TxType extends TX_TYPE.contractCall | TX_TYPE.oracleRegister
Expand Down Expand Up @@ -109,7 +116,9 @@ export async function _buildTx<TxType extends TX_TYPE> (
const senderId = params[senderKey]
// TODO: do this check on TypeScript level
if (senderId == null) throw new InvalidTxParamsError(`Transaction field ${senderKey} is missed`)
const extraParams = await prepareTxParams(txType, { ...params, senderId, denomination })
const extraParams = await prepareTxParams(
txType, { ...params, senderId, denomination, absoluteTtl }
)
return syncBuildTx({ ...params, ...extraParams } as any, txType, { denomination }).tx
}

Expand Down Expand Up @@ -161,7 +170,8 @@ export async function prepareTxParams (
vsn,
strategy,
denomination,
onNode
onNode,
...txParams
}: Pick<TxParamsCommon, 'nonce' | 'ttl' | 'fee'> & {
senderId: EncodedData<'ak'>
vsn?: number
Expand All @@ -182,6 +192,6 @@ export async function prepareTxParams (

const fee = f != null
? new BigNumber(f)
: calculateMinFee(txType, { params: { ...arguments[1], nonce, ttl }, vsn, denomination })
: calculateMinFee(txType, { params: { ...txParams, senderId, nonce, ttl }, vsn, denomination })
return { fee, ttl, nonce }
}
2 changes: 1 addition & 1 deletion src/tx/validator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ interface Account {
nonce: number
}

interface ValidatorResult {
export interface ValidatorResult {
message: string
key: string
checkedKeys: string[]
Expand Down
Loading

0 comments on commit 3fc6f6d

Please sign in to comment.