Skip to content

Return unpackTx's type in sendTransaction #1762

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

Draft
wants to merge 10 commits into
base: develop
Choose a base branch
from
1 change: 0 additions & 1 deletion docs/guides/error-handling.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,6 @@ BaseError
│ ├── EncodeError
│ ├── PayloadLengthError
│ ├── DryRunError
│ ├── IllegalBidFeeError
│ ├── InvalidSignatureError
│ ├── InvalidTxError
│ ├── PrefixNotFoundError
Expand Down
9 changes: 3 additions & 6 deletions docs/quick-start.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,16 +47,13 @@ const senderAccount = new MemoryAccount('<SENDER_SECRET_KEY>');
})

// spend one AE
await aeSdk.spend(1, '<RECIPIENT_PUBLIC_KEY>', {
// replace <RECIPIENT_PUBLIC_KEY>, Ideally you use public key from Superhero Wallet you have created before
denomination: AE_AMOUNT_FORMATS.AE
})
// replace <RECIPIENT_PUBLIC_KEY>, Ideally you use public key from Superhero Wallet you have created before
await aeSdk.spend(1e18, '<RECIPIENT_PUBLIC_KEY>')
})()
```

Note:

- You may remove code from Step 2 as this serves only for one-time creation
- By default the `spend` function expects the amount to be spent in `aettos` (the smallest possible unit)
- Following the example snippet you would specify `AE` as denomination
- The `spend` function expects the amount to be spent in `aettos` (the smallest possible unit)
- See [Testnet Explorer](https://explorer.testnet.aeternity.io/) and track your transactions
12 changes: 3 additions & 9 deletions docs/transaction-options.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ The `options` object can be optionally passed to the respective function behind
```js
const sender = 'ak_...'
const recipient = 'ak_...'
const options = { onAccount: sender, denomination: 'ae' } // optional options object
const options = { onAccount: sender } // optional options object
// aeSdk is an instance of the AeSdk class
await aeSdk.spend(1, recipient, options) // amount, recipient and (optional) options
await aeSdk.spend(1e18, recipient, options) // amount, recipient and (optional) options
```

Note:
Expand Down Expand Up @@ -48,9 +48,7 @@ The following options are sepcific for each tx-type.

### ContractCreateTx & ContractCallTx
- `amount` (default: `0`)
- To be used for providing `aettos` (or `AE` with respective denomination) to a contract related transaction.
- `denomination` (default: `aettos`)
- You can specify the denomination of the `amount` that will be provided to the contract related transaction.
- To be used for providing `aettos` to a contract related transaction.
- `gasLimit`
- Maximum amount of gas to be consumed by the transaction. Learn more on [How to estimate gas?](#how-to-estimate-gas)
- `gasPrice` (default: `1e9`)
Expand Down Expand Up @@ -91,10 +89,6 @@ The following options are sepcific for each tx-type.
- `ORACLE_TTL_TYPES.delta`: TTL value treated relative to a current block height
- `ORACLE_TTL_TYPES.block`: TTL value treated as absolute block height

### SpendTx
- `denomination` (default: `aettos`)
- You can specify the denomination of the `amount` that will be provided to the contract related transaction.

## How to estimate gas?
- As æpp developer, it is reasonable to estimate the gas consumption for a contract call using the dry-run feature of the node **once** and provide a specific offset (e.g. multiplied by 1.5 or 2) as default in the æpp to ensure that contract calls are mined. Depending on the logic of the contract the gas consumption of a specific contract call can vary and therefore you should monitor the gas consumption and increase the default for the respective contract call accordingly over time.
- By default, SDK estimates `gasLimit` using dry-run endpoint. This means an extra request that makes contract iterations slower, but it is more developer friendly (support of heavy requests without adjustments, and verbose error messages).
5 changes: 2 additions & 3 deletions src/aens.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,10 @@
* repository.
*/

import BigNumber from 'bignumber.js';
import { genSalt } from './utils/crypto';
import { commitmentHash, isAuctionName } from './tx/builder/helpers';
import {
CLIENT_TTL, NAME_TTL, Tag, AensName,
CLIENT_TTL, NAME_TTL, Tag, AensName, Int,
} from './tx/builder/constants';
import { ArgumentError } from './utils/errors';
import { Encoded } from './utils/encoder';
Expand Down Expand Up @@ -386,7 +385,7 @@ interface AensPreclaimOptions extends
*/
export async function aensBid(
name: AensName,
nameFee: number | string | BigNumber,
nameFee: Int,
options: Omit<Parameters<typeof aensClaim>[2], 'nameFee'>,
): ReturnType<typeof aensClaim> {
return aensClaim(name, 0, { ...options, nameFee });
Expand Down
18 changes: 6 additions & 12 deletions src/chain.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { AE_AMOUNT_FORMATS, formatAmount } from './utils/amount-formatter';
import verifyTransaction, { ValidatorResult } from './tx/validator';
import { isAccountNotFoundError, pause } from './utils/other';
import { isNameValid, produceNameId } from './tx/builder/helpers';
Expand Down Expand Up @@ -118,7 +117,7 @@ export async function awaitHeight(
* @category chain
* @param txHash - Transaction hash
* @param options - Options
* @param options.confirm - Number of micro blocks to wait for transaction confirmation
* @param options.confirm - Number of key blocks to wait for transaction confirmation
* @param options.onNode - Node to use
* @returns Current Height
*/
Expand Down Expand Up @@ -149,7 +148,7 @@ export async function waitForTxConfirm(
* @param options.onAccount - Account to use
* @param options.verify - Verify transaction before broadcast, throw error if not
* @param options.waitMined - Ensure that transaction get into block
* @param options.confirm - Number of micro blocks that should be mined after tx get included
* @param options.confirm - Number of key blocks that should be mined after tx get included
* @returns Transaction details
*/
export async function sendTransaction(
Expand Down Expand Up @@ -199,10 +198,7 @@ export async function sendTransaction(
// wait for transaction confirmation
if (confirm != null && (confirm === true || confirm > 0)) {
const c = typeof confirm === 'boolean' ? undefined : confirm;
return {
...txData,
confirmationHeight: await waitForTxConfirm(txHash, { onNode, confirm: c, ...options }),
};
await waitForTxConfirm(txHash, { onNode, confirm: c, ...options });
}
return txData;
}
Expand All @@ -227,7 +223,6 @@ export interface SendTransactionOptions extends SendTransactionOptionsType {}
interface SendTransactionReturnType extends Partial<TransformNodeType<SignedTx>> {
hash: Encoded.TxHash;
rawTx: Encoded.Transaction;
confirmationHeight?: number;
}

/**
Expand Down Expand Up @@ -261,9 +256,8 @@ export async function getAccount(
*/
export async function getBalance(
address: Encoded.AccountAddress | Encoded.ContractAddress | Encoded.OracleAddress,
{ format = AE_AMOUNT_FORMATS.AETTOS, ...options }:
{ format?: AE_AMOUNT_FORMATS } & Parameters<typeof getAccount>[1],
): Promise<string> {
options: Parameters<typeof getAccount>[1],
): Promise<bigint> {
const addr = address.startsWith('ok_')
? encode(decode(address), Encoding.AccountAddress)
: address as Encoded.AccountAddress | Encoded.ContractAddress;
Expand All @@ -273,7 +267,7 @@ export async function getBalance(
return { balance: 0n };
});

return formatAmount(balance, { targetDenomination: format });
return balance;
}

/**
Expand Down
9 changes: 5 additions & 4 deletions src/channel/Contract.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import BigNumber from 'bignumber.js';
import { snakeToPascal } from '../utils/string';
import {
MIN_GAS_PRICE, Tag, AbiVersion, VmVersion,
MIN_GAS_PRICE, Tag, AbiVersion, VmVersion, Int,
} from '../tx/builder/constants';
import {
signAndNotify,
Expand Down Expand Up @@ -275,14 +275,15 @@ export default class ChannelContract extends ChannelSpend {
*/
async forceProgress(
{
amount, callData, contract, abiVersion, gasLimit = 1000000, gasPrice = MIN_GAS_PRICE,
amount, callData, contract, abiVersion, gasLimit = 1000000,
gasPrice = MIN_GAS_PRICE.toString(),
}: {
amount: number;
amount: Int;
callData: Encoded.ContractBytearray;
contract: Encoded.ContractAddress;
abiVersion: AbiVersion;
gasLimit?: number;
gasPrice?: number;
gasPrice?: Int;
},
sign: SignTx,
{ onOnChainTx }: Pick<ChannelState, 'onOnChainTx'> = {},
Expand Down
4 changes: 2 additions & 2 deletions src/channel/Spend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,13 +150,13 @@ export default class ChannelSpend extends Channel {
*/
async balances(
accounts: Encoded.AccountAddress[],
): Promise<{ [key: Encoded.AccountAddress]: string }> {
): Promise<{ [key: Encoded.AccountAddress]: bigint }> {
return Object.fromEntries(
(await call(this, 'channels.get.balances', { accounts }))
.map((item: {
account: Encoded.AccountAddress;
balance: string;
}) => [item.account, item.balance]),
}) => [item.account, BigInt(item.balance)]),
);
}

Expand Down
6 changes: 3 additions & 3 deletions src/spend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import {
import { buildTxAsync, BuildTxOptions, unpackTx } from './tx/builder';
import { ArgumentError } from './utils/errors';
import { Encoded, Encoding } from './utils/encoder';
import { Tag, AensName } from './tx/builder/constants';
import { Tag, AensName, Int } from './tx/builder/constants';
import AccountBase from './account/Base';

/**
Expand All @@ -17,7 +17,7 @@ import AccountBase from './account/Base';
* @returns Transaction
*/
export async function spend(
amount: number | string,
amount: Int,
recipientIdOrName: Encoded.AccountAddress | AensName,
options: SpendOptions,
): ReturnType<typeof sendTransaction> {
Expand Down Expand Up @@ -60,7 +60,7 @@ interface SpendOptions extends SpendOptionsType {}
* ```
*/
export async function transferFunds(
fraction: number | string,
fraction: number,
recipientIdOrName: AensName | Encoded.AccountAddress,
options: TransferFundsOptions,
): ReturnType<typeof sendTransaction> {
Expand Down
6 changes: 3 additions & 3 deletions src/tx/builder/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,9 @@ export const NAME_TTL = 180000;
export const NAME_MAX_TTL = 36000;
export const NAME_MAX_CLIENT_TTL = 84600;
export const CLIENT_TTL = NAME_MAX_CLIENT_TTL;
export const MIN_GAS_PRICE = 1e9;
export const MIN_GAS_PRICE = BigInt(1e9);
// # see https://github.com/aeternity/aeternity/blob/72e440b8731422e335f879a31ecbbee7ac23a1cf/apps/aecore/src/aec_governance.erl#L67
export const NAME_FEE_MULTIPLIER = 1e14; // 100000000000000
export const NAME_FEE_MULTIPLIER = BigInt(1e14); // 100000000000000
export const NAME_FEE_BID_INCREMENT = 0.05; // # the increment is in percentage
// # see https://github.com/aeternity/aeternity/blob/72e440b8731422e335f879a31ecbbee7ac23a1cf/apps/aecore/src/aec_governance.erl#L272
export const NAME_BID_TIMEOUT_BLOCKS = 480; // # ~1 day
Expand Down Expand Up @@ -56,7 +56,7 @@ export const NAME_BID_RANGES = mapObject({
3: 2178309,
2: 3524578,
1: 5702887,
}, ([key, value]) => [key, new BigNumber(value).times(NAME_FEE_MULTIPLIER)]);
}, ([key, value]) => [key, BigInt(value) * NAME_FEE_MULTIPLIER]);

export enum ConsensusProtocolVersion {
Iris = 5,
Expand Down
19 changes: 3 additions & 16 deletions src/tx/builder/field-types/coin-amount.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,11 @@
import uInt from './u-int';
import { Int } from '../constants';
import { AE_AMOUNT_FORMATS, formatAmount } from '../../../utils/amount-formatter';

// TODO: serialize and deserialize a wrapper around bigint
export default {
...uInt,

serializeAettos(value: string | undefined): string {
return value ?? '0';
},

serialize(
value: Int | undefined,
params: {},
{ denomination = AE_AMOUNT_FORMATS.AETTOS }: { denomination?: AE_AMOUNT_FORMATS },
): Buffer {
return uInt.serialize(
this.serializeAettos(
value != null ? formatAmount(value, { denomination }) : value,
params,
),
);
serialize(value: Int | undefined): Buffer {
return uInt.serialize(value ?? 0);
},
};
14 changes: 5 additions & 9 deletions src/tx/builder/field-types/deposit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,13 @@ export default {

/**
* @param value - Deposit value in string format. Should be equal to '0'.
* @param options - Options
* @param parameters - Parameters
* @returns Deposit value Buffer.
*/
serialize(
value: Int | undefined,
options: Parameters<typeof coinAmount['serialize']>[1],
parameters: Parameters<typeof coinAmount['serialize']>[2],
): Buffer {
serialize(value: Int | undefined): Buffer {
value ??= 0;
if (+value !== 0) throw new IllegalArgumentError(`Contract deposit is not refundable, so it should be equal 0, got ${value.toString()} instead`);
return coinAmount.serialize(value, options, parameters);
if (+value !== 0) {
throw new IllegalArgumentError(`Contract deposit is not refundable, so it should be equal 0, got ${value.toString()} instead`);
}
return coinAmount.serialize(value);
},
};
Loading