Skip to content

Commit

Permalink
Merge pull request #1918 from aeternity/feature/fixes
Browse files Browse the repository at this point in the history
Non-breaking fixes from other PRs
  • Loading branch information
davidyuk authored Dec 7, 2023
2 parents c5376db + 9df3fa4 commit 13f708e
Show file tree
Hide file tree
Showing 28 changed files with 283 additions and 164 deletions.
2 changes: 1 addition & 1 deletion docs/guides/aens.md
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,7 @@ console.log(nameUpdateTx)
],
tx: {
accountId: 'ak_2519mBsgjJEVEFoRgno1ryDsn3BEaCZGRbXPEjThWYLX9MTpmk',
clientTtl: 84600,
clientTtl: 3600,
fee: 17800000000000n,
nameId: 'nm_1Cz5HGY8PMWZxNrM6s51CtsJZDU3DDT1LdmpEipa3DRghyGz5',
nameTtl: 180000,
Expand Down
1 change: 1 addition & 0 deletions docs/guides/error-handling.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ BaseError
├── UnsupportedProtocolError
├── NotImplementedError
├── UnsupportedVersionError
├── LogicError
├── InternalError
│ └── UnexpectedTsError
Expand Down
14 changes: 7 additions & 7 deletions docs/guides/oracles.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,13 @@ const oracleTtlOptions = { oracleTtlType: ORACLE_TTL_TYPES.delta, oracleTtlValue
// OR set a specific block height to expire
const oracleTtlOptions = { oracleTtlType: ORACLE_TTL_TYPES.block, oracleTtlValue: 555555 }

// queryFee is optional and defaults to 30000
// queryFee is optional and defaults to 0
// oracleTtlValue is optional and defaults to 500
// oracleTtlType is optional and defaults to ORACLE_TTL_TYPES.delta
const options = { queryFee: 1337, ...oracleTtlOptions }

// the first argument is the queryFormat and the second is the responseFormat
const oracle = await aeSdk.registerOracle("{'city': string}", "{'temperature': int}", options)
const oracle = await aeSdk.registerOracle('{"city": "str"}', '{"temperature": "int"}', options)
```

Note:
Expand All @@ -44,7 +44,7 @@ After the oracle has been registered and as long as it isn't expired, everybody
const oracleId = 'ok_...';

const options = {
queryFee: 1337, // should cover the requested fee of the oracle and defaults to 30000
queryFee: 1337, // should cover the requested fee of the oracle and defaults to 0
queryTtlType: ORACLE_TTL_TYPES.delta, // optional and defaults to ORACLE_TTL_TYPES.delta
queryTtlValue: 20, // optional and defaults to 10
responseTtlType: ORACLE_TTL_TYPES.delta, // optional and defaults to ORACLE_TTL_TYPES.delta
Expand All @@ -53,10 +53,10 @@ const options = {

// using the oracle object in case you need to instantiate the oracle object first
const oracle = await aeSdk.getOracleObject(oracleId)
const query = await oracle.postQuery("{'city': 'Berlin'}", options)
const query = await oracle.postQuery('{"city": "Berlin"}', options)

// OR using the aeSdk (instance of AeSdk class) directly by providing the oracleId
const query = await aeSdk.postQueryToOracle(oracleId, "{'city': 'Berlin'}", options)
const query = await aeSdk.postQueryToOracle(oracleId, '{"city": "Berlin"}', options)
```

Note:
Expand Down Expand Up @@ -111,10 +111,10 @@ const options = { onAccount: 'ak_...' } // only the account of the oracle can re

// using the query instance
const query = await aeSdk.getQueryObject(oracleId, queryId)
await query.respond('{ "temperature": 27.5 }', options)
await query.respond('{"temperature": 27.5}', options)

// OR using the aeSdk (instance of AeSdk class) directly by providing the queryId
await aeSdk.respondToQuery(queryId, '{ "temperature": 27.5 }', options)
await aeSdk.respondToQuery(queryId, '{"temperature": 27.5}', options)
```

Note:
Expand Down
6 changes: 3 additions & 3 deletions docs/transaction-options.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,14 +62,14 @@ The following options are sepcific for each tx-type.
- For bids in an auction you need to explicitely calculate the required `nameFee` based on the last bid

### NameUpdateTx
- `clientTtl` (default: `84600`)
- `clientTtl` (default: `3600`, one hour)
- This option is an indicator for indexing tools to know how long (in seconds) they could or should cache the name information.
- `nameTtl` (default: `180000`)
- This option tells the protocol the relative TTL based on the current block height.
- `180000` is the maximum possible value

### OracleRegisterTx
- `queryFee` (default: `30000`)
- `queryFee` (default: `0`)
- The fee in `aettos` that the oracle requests in order to provide a response.
- `oracleTtlValue` (default: `500`)
- The TTL of the oracle that defines its expiration.
Expand All @@ -78,7 +78,7 @@ The following options are sepcific for each tx-type.
- `ORACLE_TTL_TYPES.block`: TTL value treated as absolute block height

### OracleQueryTx
- `queryFee` (default: `30000`)
- `queryFee` (default: `0`)
- The fee in `aettos` that will be payed to the oracle.
- `queryTtlValue` (default: `10`)
- The TTL of the query that defines its expiration. The oracle needs to respond before the `queryTtl` expires.
Expand Down
12 changes: 9 additions & 3 deletions src/AeSdkBase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,11 @@ export default class AeSdkBase extends AeSdkMethods {
.signOracleQueryDelegationToContract(contractAddress, oracleQueryId, options);
}

override _getOptions(callOptions: AeSdkMethodsOptions = {}): {
/**
* The same as AeSdkMethods:getContext, but it would resolve ak_-prefixed address in
* `mergeWith.onAccount` to AccountBase.
*/
override getContext(mergeWith: AeSdkMethodsOptions = {}): AeSdkMethodsOptions & {
onNode: Node;
onAccount: AccountBase;
onCompiler: CompilerBase;
Expand All @@ -221,8 +225,10 @@ export default class AeSdkBase extends AeSdkMethods {
...this._options,
onNode: getValueOrErrorProxy(() => this.api),
onCompiler: getValueOrErrorProxy(() => this.compilerApi),
...callOptions,
onAccount: getValueOrErrorProxy(() => this._resolveAccount(callOptions.onAccount)),
...mergeWith,
onAccount: mergeWith.onAccount != null
? this._resolveAccount(mergeWith.onAccount)
: getValueOrErrorProxy(() => this._resolveAccount()),
};
}
}
18 changes: 12 additions & 6 deletions src/AeSdkMethods.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,26 +80,32 @@ class AeSdkMethods {
Object.assign(this._options, options);
}

_getOptions(
callOptions: AeSdkMethodsOptions = {},
/**
* Returns sdk instance options with references to current account, node, compiler.
* Used to create an instance (Contract, Oracle) bound to AeSdk state.
* @param mergeWith - Merge context with these extra options
* @returns Context object
*/
getContext(
mergeWith: AeSdkMethodsOptions = {},
): AeSdkMethodsOptions & { onAccount: AccountBase; onCompiler: CompilerBase; onNode: Node } {
return {
...this._options,
onAccount: getValueOrErrorProxy(() => this._options.onAccount),
onNode: getValueOrErrorProxy(() => this._options.onNode),
onCompiler: getValueOrErrorProxy(() => this._options.onCompiler),
...callOptions,
...mergeWith,
};
}

async buildTx(options: TxParamsAsync): Promise<Encoded.Transaction> {
return buildTxAsync({ ...this._getOptions(), ...options });
return buildTxAsync({ ...this.getContext(), ...options });
}

async initializeContract<Methods extends ContractMethodsBase>(
options?: Omit<Parameters<typeof Contract.initialize>[0], 'onNode'> & { onNode?: Node },
): Promise<Contract<Methods>> {
return Contract.initialize<Methods>(this._getOptions(options as AeSdkMethodsOptions));
return Contract.initialize<Methods>(this.getContext(options as AeSdkMethodsOptions));
}
}

Expand Down Expand Up @@ -133,7 +139,7 @@ Object.assign(AeSdkMethods.prototype, mapObject<Function, Function>(
function methodWrapper(this: AeSdkMethods, ...args: any[]) {
args.length = handler.length;
const options = args[args.length - 1];
args[args.length - 1] = this._getOptions(options);
args[args.length - 1] = this.getContext(options);
return handler(...args);
},
],
Expand Down
4 changes: 4 additions & 0 deletions src/Node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,10 @@ export default class Node extends (NodeTransformed as unknown as NodeTransformed
this.intAsString = true;
}

/**
* Returns network ID provided by node.
* This method won't do extra requests on subsequent calls.
*/
async getNetworkId(): Promise<string> {
this.#networkIdPromise ??= this.getStatus().then(({ networkId }) => networkId);
const networkId = await this.#networkIdPromise;
Expand Down
15 changes: 3 additions & 12 deletions src/aens.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,7 @@
import BigNumber from 'bignumber.js';
import { genSalt } from './utils/crypto';
import { commitmentHash, isAuctionName } from './tx/builder/helpers';
import {
CLIENT_TTL, NAME_TTL, Tag, AensName,
} from './tx/builder/constants';
import { ArgumentError } from './utils/errors';
import { Tag, AensName } from './tx/builder/constants';
import { Encoded } from './utils/encoder';
import { sendTransaction, SendTransactionOptions, getName } from './chain';
import { buildTxAsync, BuildTxOptions } from './tx/builder';
Expand Down Expand Up @@ -78,7 +75,7 @@ interface AensRevokeOptions extends
* @param options.nonce - nonce
* @param options.nameTtl - Name ttl represented in number of
* blocks (Max value is 50000 blocks)
* @param options.clientTtl=84600 a suggestion as to how long any
* @param options.clientTtl a suggestion as to how long any
* clients should cache this information
* @throws Invalid pointer array error
* @example
Expand All @@ -105,8 +102,6 @@ export async function aensUpdate(
};

const nameUpdateTx = await buildTxAsync({
clientTtl: CLIENT_TTL,
nameTtl: NAME_TTL,
...options,
tag: Tag.NameUpdateTx,
nameId: name,
Expand Down Expand Up @@ -240,11 +235,7 @@ export async function aensQuery(
async revoke(options) {
return aensRevoke(name, { ...opt, ...options });
},
async extendTtl(nameTtl = NAME_TTL, options = {}) {
if (nameTtl > NAME_TTL || nameTtl <= 0) {
throw new ArgumentError('nameTtl', `a number between 1 and ${NAME_TTL} blocks`, nameTtl);
}

async extendTtl(nameTtl, options = {}) {
return {
...await aensUpdate(name, {}, {
...opt, ...options, nameTtl, extendPointers: true,
Expand Down
36 changes: 36 additions & 0 deletions src/deprecated.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { TypeResolver, ContractByteArrayEncoder } from '@aeternity/aepp-calldata
import { AciValue } from './utils/typed-data';
import { Encoded } from './utils/encoder';
import { RpcError } from './aepp-wallet-communication/schema';
import { ORACLE_TTL_TYPES } from './tx/builder/schema';

/**
* @category exception
Expand Down Expand Up @@ -39,3 +40,38 @@ export function decodeFateValue(value: Encoded.ContractBytearray, aci: AciValue)
const valueType = new TypeResolver().resolveType(aci, {});
return new ContractByteArrayEncoder().decodeWithType(value, valueType);
}

/**
* @deprecated inlined in buildTx or use `180000`
*/
export const NAME_TTL = 180000;

/**
* @deprecated inlined in buildTx or use `36000`
*/
export const NAME_MAX_TTL = 36000;

/**
* @deprecated inlined in buildTx or use `60 * 60`
*/
export const NAME_MAX_CLIENT_TTL = 60 * 60;

/**
* @deprecated inlined in buildTx or use `60 * 60`
*/
export const CLIENT_TTL = NAME_MAX_CLIENT_TTL;

/**
* @deprecated inlined in buildTx or use `{ type: ORACLE_TTL_TYPES.delta, value: 500 }`
*/
export const ORACLE_TTL = { type: ORACLE_TTL_TYPES.delta, value: 500 };

/**
* @deprecated inlined in buildTx or use `{ type: ORACLE_TTL_TYPES.delta, value: 10 }`
*/
export const QUERY_TTL = { type: ORACLE_TTL_TYPES.delta, value: 10 };

/**
* @deprecated inlined in buildTx or use `{ type: ORACLE_TTL_TYPES.delta, value: 10 }`
*/
export const RESPONSE_TTL = { type: ORACLE_TTL_TYPES.delta, value: 10 };
10 changes: 5 additions & 5 deletions src/index-browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,15 +20,13 @@ export {
getDefaultPointerKey, getMinimumNameFee, computeBidFee, computeAuctionEndBlock, isAuctionName,
} from './tx/builder/helpers';
export {
MAX_AUTH_FUN_GAS, NAME_TTL, NAME_MAX_TTL, NAME_MAX_CLIENT_TTL, CLIENT_TTL, MIN_GAS_PRICE,
MAX_AUTH_FUN_GAS, MIN_GAS_PRICE,
NAME_FEE_MULTIPLIER, NAME_FEE_BID_INCREMENT, NAME_BID_TIMEOUT_BLOCKS, NAME_MAX_LENGTH_FEE,
NAME_BID_RANGES, ConsensusProtocolVersion, VmVersion, AbiVersion, Tag,
} from './tx/builder/constants';
export type { Int, AensName } from './tx/builder/constants';
// TODO: move to constants
export {
ORACLE_TTL_TYPES, ORACLE_TTL, QUERY_TTL, RESPONSE_TTL, DRY_RUN_ACCOUNT, CallReturnType,
} from './tx/builder/schema';
export { ORACLE_TTL_TYPES, DRY_RUN_ACCOUNT, CallReturnType } from './tx/builder/schema';
export {
getExecutionCost, getExecutionCostBySignedTx, getExecutionCostUsingNode,
} from './tx/execution-cost';
Expand Down Expand Up @@ -93,7 +91,7 @@ export {
CryptographyError, NodeError, TransactionError, WalletError, ArgumentError, IllegalArgumentError,
ArgumentCountMismatchError, InsufficientBalanceError, MissingParamError, NoSerializerFoundError,
RequestTimedOutError, TxTimedOutError, TypeError, UnsupportedPlatformError,
UnsupportedProtocolError, NotImplementedError, UnsupportedVersionError, InternalError,
UnsupportedProtocolError, NotImplementedError, UnsupportedVersionError, LogicError, InternalError,
UnexpectedTsError, UnavailableAccountError, AensPointerContextError, InsufficientNameFeeError,
InvalidAensNameError, InvalidRpcMessageError, MissingCallbackError, UnAuthorizedAccountError,
UnknownRpcClientError, UnsubscribedAccountError, ChannelCallError, ChannelConnectionError,
Expand All @@ -111,4 +109,6 @@ export {
} from './utils/errors';
export {
RpcBroadcastError, NAME_BID_MAX_LENGTH, encodeFateValue, decodeFateValue,
NAME_TTL, NAME_MAX_TTL, NAME_MAX_CLIENT_TTL, CLIENT_TTL,
ORACLE_TTL, QUERY_TTL, RESPONSE_TTL,
} from './deprecated';
Loading

0 comments on commit 13f708e

Please sign in to comment.