PHP WebShell
Текущая директория: /opt/BitGoJS/node_modules/@aptos-labs/ts-sdk/dist/common
Просмотр файла: index.d.ts
import { S as Serializable, T as TransactionArgument, H as HexInput, a as Serializer, D as Deserializer, E as EntryFunctionArgument, U as Uint8, b as Uint16, c as Uint32, A as AnyNumber, d as Deserializable, e as Hex, f as AuthenticationKeyScheme, g as AccountAddress, P as PrivateKeyVariants, h as AnyPublicKeyVariant, i as EphemeralPublicKeyVariant, N as Network, C as Client, j as ClientConfig, F as FullNodeConfig, I as IndexerConfig, k as FaucetConfig, l as AptosSettings, m as EphemeralCertificateVariant, Z as ZkpVariant, L as LedgerVersionArg, n as AccountAddressInput, M as MoveModuleId, o as ScriptFunctionArgument, p as MoveFunctionId, q as MoveStructId, r as MoveValue, s as MoveFunctionGenericTypeParam, t as SigningSchemeInput, u as SigningScheme, v as AccountData, w as PaginationArgs, x as MoveModuleBytecode, y as TransactionResponse, z as MoveResource, B as TokenStandardArg, O as OrderByArg, G as GetAccountOwnedTokensQueryResponse, J as GetAccountOwnedTokensFromCollectionResponse, K as GetAccountCollectionsWithOwnedTokenResponse, Q as GetAccountCoinsDataResponse, W as WhereArg, R as GetObjectDataQueryResponse, V as GetCollectionDataResponse, X as GetTokenDataResponse, Y as GetCurrentTokenOwnershipResponse, _ as GetOwnedTokensResponse, $ as GetTokenActivityResponse, a0 as GetEventsResponse, a1 as WaitForTransactionOptions, a2 as UserTransactionResponse, a3 as MoveFunction, a4 as GetFungibleAssetMetadataResponse, a5 as GetFungibleAssetActivitiesResponse, a6 as GetCurrentFungibleAssetBalancesResponse, a7 as LedgerInfo, a8 as Block, a9 as GetChainTopUserTransactionsResponse, aa as GraphqlQuery, ab as GetProcessorStatusResponse, ac as GetANSNameResponse, ad as GetNumberOfDelegatorsResponse, ae as GetDelegatedStakingActivitiesResponse, af as PendingTransactionResponse, ag as CommittedTransactionResponse, ah as GasEstimation, ai as TableItemRequest, aj as GetTableItemsDataResponse, ak as GetTableItemsMetadataResponse, al as ClientRequest, am as ClientResponse, an as AptosRequest, ao as AptosResponse, ap as MimeType } from './accountAddress-BHsGaOsa.js';
export { aG as AccountAuthenticatorVariant, bp as AccountSignature, at as AddressInvalidReason, aH as AnySignatureVariant, aZ as BlockEndInfo, a_ as BlockEpilogueTransactionResponse, aW as BlockMetadataTransactionResponse, aM as ClientHeadersType, b6 as DecodedTableData, b7 as DeletedTableData, bM as DeriveScheme, bs as DirectWriteSet, b9 as EntryFunctionPayloadResponse, aI as EphemeralSignatureVariant, bu as Event, bt as EventGuid, bP as GenerateAccount, bN as GenerateAccountWithEd25519, bO as GenerateAccountWithSingleSignerSecp256k1Key, bc as GenesisPayload, aV as GenesisTransactionResponse, aw as HexInvalidReason, bH as MoveAbility, bB as MoveAddressType, bG as MoveFunctionVisibility, bJ as MoveModule, bC as MoveObjectType, bD as MoveOptionType, bd as MoveScriptBytecode, bK as MoveStruct, bI as MoveStructField, bE as MoveStructType, bF as MoveType, bz as MoveUint128Type, bw as MoveUint16Type, bA as MoveUint256Type, bx as MoveUint32Type, by as MoveUint64Type, bv as MoveUint8Type, bb as MultisigPayloadResponse, bV as NetworkToChainId, bS as NetworkToFaucetAPI, bQ as NetworkToIndexerAPI, bW as NetworkToNetworkName, bR as NetworkToNodeAPI, bT as NetworkToPepperAPI, bU as NetworkToProverAPI, ay as OrderBy, az as OrderByValue, au as ParsingError, av as ParsingResult, bL as RoleType, ba as ScriptPayloadResponse, aC as ScriptTransactionArgumentVariants, br as ScriptWriteSet, aX as StateCheckpointTransactionResponse, aA as TokenStandard, aF as TransactionAuthenticatorVariant, bk as TransactionEd25519Signature, bo as TransactionFeePayerSignature, bn as TransactionMultiAgentSignature, bm as TransactionMultiEd25519Signature, b8 as TransactionPayloadResponse, aD as TransactionPayloadVariants, aN as TransactionResponseType, bl as TransactionSecp256k1Signature, be as TransactionSignature, aE as TransactionVariants, aB as TypeTagVariants, aK as Uint128, aL as Uint256, aJ as Uint64, aY as ValidatorTransactionResponse, bq as WriteSet, a$ as WriteSetChange, b0 as WriteSetChangeDeleteModule, b1 as WriteSetChangeDeleteResource, b2 as WriteSetChangeDeleteTableItem, b3 as WriteSetChangeWriteModule, b4 as WriteSetChangeWriteResource, b5 as WriteSetChangeWriteTableItem, aq as ensureBoolean, ax as hexToAsciiString, aU as isBlockEpilogueTransactionResponse, aR as isBlockMetadataTransactionResponse, bf as isEd25519Signature, bi as isFeePayerSignature, aQ as isGenesisTransactionResponse, bh as isMultiAgentSignature, bj as isMultiEd25519Signature, aO as isPendingTransactionResponse, bg as isSecp256k1Signature, aS as isStateCheckpointTransactionResponse, aP as isUserTransactionResponse, aT as isValidatorTransactionResponse, ar as outOfRangeErrorMessage, as as validateNumberInRange } from './accountAddress-BHsGaOsa.js';
import EventEmitter from 'eventemitter3';
type Maybe<T> = T | null;
type InputMaybe<T> = Maybe<T>;
/** All built-in and custom scalars, mapped to their actual values */
type Scalars = {
ID: {
input: string;
output: string;
};
String: {
input: string;
output: string;
};
Boolean: {
input: boolean;
output: boolean;
};
Int: {
input: number;
output: number;
};
Float: {
input: number;
output: number;
};
bigint: {
input: any;
output: any;
};
jsonb: {
input: any;
output: any;
};
numeric: {
input: any;
output: any;
};
timestamp: {
input: any;
output: any;
};
timestamptz: {
input: any;
output: any;
};
};
/** Boolean expression to compare columns of type "Boolean". All fields are combined with logical 'AND'. */
type BooleanComparisonExp = {
_eq?: InputMaybe<Scalars["Boolean"]["input"]>;
_gt?: InputMaybe<Scalars["Boolean"]["input"]>;
_gte?: InputMaybe<Scalars["Boolean"]["input"]>;
_in?: InputMaybe<Array<Scalars["Boolean"]["input"]>>;
_is_null?: InputMaybe<Scalars["Boolean"]["input"]>;
_lt?: InputMaybe<Scalars["Boolean"]["input"]>;
_lte?: InputMaybe<Scalars["Boolean"]["input"]>;
_neq?: InputMaybe<Scalars["Boolean"]["input"]>;
_nin?: InputMaybe<Array<Scalars["Boolean"]["input"]>>;
};
/** Boolean expression to compare columns of type "Int". All fields are combined with logical 'AND'. */
type IntComparisonExp = {
_eq?: InputMaybe<Scalars["Int"]["input"]>;
_gt?: InputMaybe<Scalars["Int"]["input"]>;
_gte?: InputMaybe<Scalars["Int"]["input"]>;
_in?: InputMaybe<Array<Scalars["Int"]["input"]>>;
_is_null?: InputMaybe<Scalars["Boolean"]["input"]>;
_lt?: InputMaybe<Scalars["Int"]["input"]>;
_lte?: InputMaybe<Scalars["Int"]["input"]>;
_neq?: InputMaybe<Scalars["Int"]["input"]>;
_nin?: InputMaybe<Array<Scalars["Int"]["input"]>>;
};
/** Boolean expression to compare columns of type "String". All fields are combined with logical 'AND'. */
type StringComparisonExp = {
_eq?: InputMaybe<Scalars["String"]["input"]>;
_gt?: InputMaybe<Scalars["String"]["input"]>;
_gte?: InputMaybe<Scalars["String"]["input"]>;
/** does the column match the given case-insensitive pattern */
_ilike?: InputMaybe<Scalars["String"]["input"]>;
_in?: InputMaybe<Array<Scalars["String"]["input"]>>;
/** does the column match the given POSIX regular expression, case insensitive */
_iregex?: InputMaybe<Scalars["String"]["input"]>;
_is_null?: InputMaybe<Scalars["Boolean"]["input"]>;
/** does the column match the given pattern */
_like?: InputMaybe<Scalars["String"]["input"]>;
_lt?: InputMaybe<Scalars["String"]["input"]>;
_lte?: InputMaybe<Scalars["String"]["input"]>;
_neq?: InputMaybe<Scalars["String"]["input"]>;
/** does the column NOT match the given case-insensitive pattern */
_nilike?: InputMaybe<Scalars["String"]["input"]>;
_nin?: InputMaybe<Array<Scalars["String"]["input"]>>;
/** does the column NOT match the given POSIX regular expression, case insensitive */
_niregex?: InputMaybe<Scalars["String"]["input"]>;
/** does the column NOT match the given pattern */
_nlike?: InputMaybe<Scalars["String"]["input"]>;
/** does the column NOT match the given POSIX regular expression, case sensitive */
_nregex?: InputMaybe<Scalars["String"]["input"]>;
/** does the column NOT match the given SQL regular expression */
_nsimilar?: InputMaybe<Scalars["String"]["input"]>;
/** does the column match the given POSIX regular expression, case sensitive */
_regex?: InputMaybe<Scalars["String"]["input"]>;
/** does the column match the given SQL regular expression */
_similar?: InputMaybe<Scalars["String"]["input"]>;
};
/** Boolean expression to compare columns of type "bigint". All fields are combined with logical 'AND'. */
type BigintComparisonExp = {
_eq?: InputMaybe<Scalars["bigint"]["input"]>;
_gt?: InputMaybe<Scalars["bigint"]["input"]>;
_gte?: InputMaybe<Scalars["bigint"]["input"]>;
_in?: InputMaybe<Array<Scalars["bigint"]["input"]>>;
_is_null?: InputMaybe<Scalars["Boolean"]["input"]>;
_lt?: InputMaybe<Scalars["bigint"]["input"]>;
_lte?: InputMaybe<Scalars["bigint"]["input"]>;
_neq?: InputMaybe<Scalars["bigint"]["input"]>;
_nin?: InputMaybe<Array<Scalars["bigint"]["input"]>>;
};
type CurrentAptosNamesAggregateBoolExp = {
bool_and?: InputMaybe<CurrentAptosNamesAggregateBoolExpBoolAnd>;
bool_or?: InputMaybe<CurrentAptosNamesAggregateBoolExpBoolOr>;
count?: InputMaybe<CurrentAptosNamesAggregateBoolExpCount>;
};
type CurrentAptosNamesAggregateBoolExpBoolAnd = {
arguments: CurrentAptosNamesSelectColumnCurrentAptosNamesAggregateBoolExpBoolAndArgumentsColumns;
distinct?: InputMaybe<Scalars["Boolean"]["input"]>;
filter?: InputMaybe<CurrentAptosNamesBoolExp>;
predicate: BooleanComparisonExp;
};
type CurrentAptosNamesAggregateBoolExpBoolOr = {
arguments: CurrentAptosNamesSelectColumnCurrentAptosNamesAggregateBoolExpBoolOrArgumentsColumns;
distinct?: InputMaybe<Scalars["Boolean"]["input"]>;
filter?: InputMaybe<CurrentAptosNamesBoolExp>;
predicate: BooleanComparisonExp;
};
type CurrentAptosNamesAggregateBoolExpCount = {
arguments?: InputMaybe<Array<CurrentAptosNamesSelectColumn>>;
distinct?: InputMaybe<Scalars["Boolean"]["input"]>;
filter?: InputMaybe<CurrentAptosNamesBoolExp>;
predicate: IntComparisonExp;
};
/** Boolean expression to filter rows from the table "current_aptos_names". All fields are combined with a logical 'AND'. */
type CurrentAptosNamesBoolExp = {
_and?: InputMaybe<Array<CurrentAptosNamesBoolExp>>;
_not?: InputMaybe<CurrentAptosNamesBoolExp>;
_or?: InputMaybe<Array<CurrentAptosNamesBoolExp>>;
domain?: InputMaybe<StringComparisonExp>;
domain_expiration_timestamp?: InputMaybe<TimestampComparisonExp>;
domain_with_suffix?: InputMaybe<StringComparisonExp>;
expiration_timestamp?: InputMaybe<TimestampComparisonExp>;
is_active?: InputMaybe<BooleanComparisonExp>;
is_domain_owner?: InputMaybe<CurrentAptosNamesBoolExp>;
is_primary?: InputMaybe<BooleanComparisonExp>;
last_transaction_version?: InputMaybe<BigintComparisonExp>;
owner_address?: InputMaybe<StringComparisonExp>;
registered_address?: InputMaybe<StringComparisonExp>;
subdomain?: InputMaybe<StringComparisonExp>;
subdomain_expiration_policy?: InputMaybe<BigintComparisonExp>;
token_name?: InputMaybe<StringComparisonExp>;
token_standard?: InputMaybe<StringComparisonExp>;
};
/** select columns of table "current_aptos_names" */
declare enum CurrentAptosNamesSelectColumn {
/** column name */
Domain = "domain",
/** column name */
DomainExpirationTimestamp = "domain_expiration_timestamp",
/** column name */
DomainWithSuffix = "domain_with_suffix",
/** column name */
ExpirationTimestamp = "expiration_timestamp",
/** column name */
IsActive = "is_active",
/** column name */
IsPrimary = "is_primary",
/** column name */
LastTransactionVersion = "last_transaction_version",
/** column name */
OwnerAddress = "owner_address",
/** column name */
RegisteredAddress = "registered_address",
/** column name */
Subdomain = "subdomain",
/** column name */
SubdomainExpirationPolicy = "subdomain_expiration_policy",
/** column name */
TokenName = "token_name",
/** column name */
TokenStandard = "token_standard"
}
/** select "current_aptos_names_aggregate_bool_exp_bool_and_arguments_columns" columns of table "current_aptos_names" */
declare enum CurrentAptosNamesSelectColumnCurrentAptosNamesAggregateBoolExpBoolAndArgumentsColumns {
/** column name */
IsActive = "is_active",
/** column name */
IsPrimary = "is_primary"
}
/** select "current_aptos_names_aggregate_bool_exp_bool_or_arguments_columns" columns of table "current_aptos_names" */
declare enum CurrentAptosNamesSelectColumnCurrentAptosNamesAggregateBoolExpBoolOrArgumentsColumns {
/** column name */
IsActive = "is_active",
/** column name */
IsPrimary = "is_primary"
}
/** Boolean expression to filter rows from the table "current_unified_fungible_asset_balances_to_be_renamed". All fields are combined with a logical 'AND'. */
type CurrentFungibleAssetBalancesBoolExp = {
_and?: InputMaybe<Array<CurrentFungibleAssetBalancesBoolExp>>;
_not?: InputMaybe<CurrentFungibleAssetBalancesBoolExp>;
_or?: InputMaybe<Array<CurrentFungibleAssetBalancesBoolExp>>;
amount?: InputMaybe<NumericComparisonExp>;
asset_type?: InputMaybe<StringComparisonExp>;
is_frozen?: InputMaybe<BooleanComparisonExp>;
is_primary?: InputMaybe<BooleanComparisonExp>;
last_transaction_timestamp?: InputMaybe<TimestampComparisonExp>;
last_transaction_version?: InputMaybe<BigintComparisonExp>;
metadata?: InputMaybe<FungibleAssetMetadataBoolExp>;
owner_address?: InputMaybe<StringComparisonExp>;
storage_id?: InputMaybe<StringComparisonExp>;
token_standard?: InputMaybe<StringComparisonExp>;
};
/** Boolean expression to filter rows from the table "events". All fields are combined with a logical 'AND'. */
type EventsBoolExp = {
_and?: InputMaybe<Array<EventsBoolExp>>;
_not?: InputMaybe<EventsBoolExp>;
_or?: InputMaybe<Array<EventsBoolExp>>;
account_address?: InputMaybe<StringComparisonExp>;
creation_number?: InputMaybe<BigintComparisonExp>;
data?: InputMaybe<JsonbComparisonExp>;
event_index?: InputMaybe<BigintComparisonExp>;
indexed_type?: InputMaybe<StringComparisonExp>;
sequence_number?: InputMaybe<BigintComparisonExp>;
transaction_block_height?: InputMaybe<BigintComparisonExp>;
transaction_version?: InputMaybe<BigintComparisonExp>;
type?: InputMaybe<StringComparisonExp>;
};
/** Boolean expression to filter rows from the table "fungible_asset_activities". All fields are combined with a logical 'AND'. */
type FungibleAssetActivitiesBoolExp = {
_and?: InputMaybe<Array<FungibleAssetActivitiesBoolExp>>;
_not?: InputMaybe<FungibleAssetActivitiesBoolExp>;
_or?: InputMaybe<Array<FungibleAssetActivitiesBoolExp>>;
amount?: InputMaybe<NumericComparisonExp>;
asset_type?: InputMaybe<StringComparisonExp>;
block_height?: InputMaybe<BigintComparisonExp>;
entry_function_id_str?: InputMaybe<StringComparisonExp>;
event_index?: InputMaybe<BigintComparisonExp>;
gas_fee_payer_address?: InputMaybe<StringComparisonExp>;
is_frozen?: InputMaybe<BooleanComparisonExp>;
is_gas_fee?: InputMaybe<BooleanComparisonExp>;
is_transaction_success?: InputMaybe<BooleanComparisonExp>;
metadata?: InputMaybe<FungibleAssetMetadataBoolExp>;
owner_address?: InputMaybe<StringComparisonExp>;
owner_aptos_names?: InputMaybe<CurrentAptosNamesBoolExp>;
owner_aptos_names_aggregate?: InputMaybe<CurrentAptosNamesAggregateBoolExp>;
storage_id?: InputMaybe<StringComparisonExp>;
storage_refund_amount?: InputMaybe<NumericComparisonExp>;
token_standard?: InputMaybe<StringComparisonExp>;
transaction_timestamp?: InputMaybe<TimestampComparisonExp>;
transaction_version?: InputMaybe<BigintComparisonExp>;
type?: InputMaybe<StringComparisonExp>;
};
/** Boolean expression to filter rows from the table "fungible_asset_metadata". All fields are combined with a logical 'AND'. */
type FungibleAssetMetadataBoolExp = {
_and?: InputMaybe<Array<FungibleAssetMetadataBoolExp>>;
_not?: InputMaybe<FungibleAssetMetadataBoolExp>;
_or?: InputMaybe<Array<FungibleAssetMetadataBoolExp>>;
asset_type?: InputMaybe<StringComparisonExp>;
creator_address?: InputMaybe<StringComparisonExp>;
decimals?: InputMaybe<IntComparisonExp>;
icon_uri?: InputMaybe<StringComparisonExp>;
last_transaction_timestamp?: InputMaybe<TimestampComparisonExp>;
last_transaction_version?: InputMaybe<BigintComparisonExp>;
maximum_v2?: InputMaybe<NumericComparisonExp>;
name?: InputMaybe<StringComparisonExp>;
project_uri?: InputMaybe<StringComparisonExp>;
supply_aggregator_table_handle_v1?: InputMaybe<StringComparisonExp>;
supply_aggregator_table_key_v1?: InputMaybe<StringComparisonExp>;
supply_v2?: InputMaybe<NumericComparisonExp>;
symbol?: InputMaybe<StringComparisonExp>;
token_standard?: InputMaybe<StringComparisonExp>;
};
type JsonbCastExp = {
String?: InputMaybe<StringComparisonExp>;
};
/** Boolean expression to compare columns of type "jsonb". All fields are combined with logical 'AND'. */
type JsonbComparisonExp = {
_cast?: InputMaybe<JsonbCastExp>;
/** is the column contained in the given json value */
_contained_in?: InputMaybe<Scalars["jsonb"]["input"]>;
/** does the column contain the given json value at the top level */
_contains?: InputMaybe<Scalars["jsonb"]["input"]>;
_eq?: InputMaybe<Scalars["jsonb"]["input"]>;
_gt?: InputMaybe<Scalars["jsonb"]["input"]>;
_gte?: InputMaybe<Scalars["jsonb"]["input"]>;
/** does the string exist as a top-level key in the column */
_has_key?: InputMaybe<Scalars["String"]["input"]>;
/** do all of these strings exist as top-level keys in the column */
_has_keys_all?: InputMaybe<Array<Scalars["String"]["input"]>>;
/** do any of these strings exist as top-level keys in the column */
_has_keys_any?: InputMaybe<Array<Scalars["String"]["input"]>>;
_in?: InputMaybe<Array<Scalars["jsonb"]["input"]>>;
_is_null?: InputMaybe<Scalars["Boolean"]["input"]>;
_lt?: InputMaybe<Scalars["jsonb"]["input"]>;
_lte?: InputMaybe<Scalars["jsonb"]["input"]>;
_neq?: InputMaybe<Scalars["jsonb"]["input"]>;
_nin?: InputMaybe<Array<Scalars["jsonb"]["input"]>>;
};
/** Boolean expression to compare columns of type "numeric". All fields are combined with logical 'AND'. */
type NumericComparisonExp = {
_eq?: InputMaybe<Scalars["numeric"]["input"]>;
_gt?: InputMaybe<Scalars["numeric"]["input"]>;
_gte?: InputMaybe<Scalars["numeric"]["input"]>;
_in?: InputMaybe<Array<Scalars["numeric"]["input"]>>;
_is_null?: InputMaybe<Scalars["Boolean"]["input"]>;
_lt?: InputMaybe<Scalars["numeric"]["input"]>;
_lte?: InputMaybe<Scalars["numeric"]["input"]>;
_neq?: InputMaybe<Scalars["numeric"]["input"]>;
_nin?: InputMaybe<Array<Scalars["numeric"]["input"]>>;
};
/** Boolean expression to filter rows from the table "table_items". All fields are combined with a logical 'AND'. */
type TableItemsBoolExp = {
_and?: InputMaybe<Array<TableItemsBoolExp>>;
_not?: InputMaybe<TableItemsBoolExp>;
_or?: InputMaybe<Array<TableItemsBoolExp>>;
decoded_key?: InputMaybe<JsonbComparisonExp>;
decoded_value?: InputMaybe<JsonbComparisonExp>;
key?: InputMaybe<StringComparisonExp>;
table_handle?: InputMaybe<StringComparisonExp>;
transaction_version?: InputMaybe<BigintComparisonExp>;
write_set_change_index?: InputMaybe<BigintComparisonExp>;
};
/** Boolean expression to filter rows from the table "table_metadatas". All fields are combined with a logical 'AND'. */
type TableMetadatasBoolExp = {
_and?: InputMaybe<Array<TableMetadatasBoolExp>>;
_not?: InputMaybe<TableMetadatasBoolExp>;
_or?: InputMaybe<Array<TableMetadatasBoolExp>>;
handle?: InputMaybe<StringComparisonExp>;
key_type?: InputMaybe<StringComparisonExp>;
value_type?: InputMaybe<StringComparisonExp>;
};
/** Boolean expression to compare columns of type "timestamp". All fields are combined with logical 'AND'. */
type TimestampComparisonExp = {
_eq?: InputMaybe<Scalars["timestamp"]["input"]>;
_gt?: InputMaybe<Scalars["timestamp"]["input"]>;
_gte?: InputMaybe<Scalars["timestamp"]["input"]>;
_in?: InputMaybe<Array<Scalars["timestamp"]["input"]>>;
_is_null?: InputMaybe<Scalars["Boolean"]["input"]>;
_lt?: InputMaybe<Scalars["timestamp"]["input"]>;
_lte?: InputMaybe<Scalars["timestamp"]["input"]>;
_neq?: InputMaybe<Scalars["timestamp"]["input"]>;
_nin?: InputMaybe<Array<Scalars["timestamp"]["input"]>>;
};
/**
* Represents a contiguous sequence of already serialized BCS bytes.
*
* This class differs from most other Serializable classes in that its internal byte buffer is serialized to BCS
* bytes exactly as-is, without prepending the length of the bytes. It is ideal for scenarios where custom serialization
* is required, such as passing serialized bytes as transaction arguments. Additionally, it serves as a representation
* of type-agnostic BCS bytes, akin to a vector<u8>.
*
* An example use case includes handling bytes resulting from entry function arguments that have been serialized
* for an entry function.
*
* @example
* const yourCustomSerializedBytes = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
* const fixedBytes = new FixedBytes(yourCustomSerializedBytes);
* const payload = await generateTransactionPayload({
* function: "0xbeefcafe::your_module::your_function_that_requires_custom_serialization",
* functionArguments: [yourCustomBytes],
* });
*
* This class is particularly useful when you want to handle a fixed-size byte array without the overhead of
* length prepending, such as when dealing with 32-byte addresses stored as U8 in a MoveVector<U8>.
* For example, if you store each of the 32 bytes for an address as a U8 in a MoveVector<U8>, when you
* serialize that MoveVector<U8>, it will be serialized to 33 bytes. If you solely want to pass around
* the 32 bytes as a Serializable class that *does not* prepend the length to the BCS-serialized representation,
* use this class.*
* @param value - HexInput representing a sequence of Uint8 bytes.
* @returns A Serializable FixedBytes instance, which when serialized, does not prepend the length of the bytes.
* @see EntryFunctionBytes
*/
declare class FixedBytes extends Serializable implements TransactionArgument {
value: Uint8Array;
/**
* Creates an instance of the class with a specified hexadecimal input.
* The value is converted from hexadecimal format to a Uint8Array.
*
* @param value - The hexadecimal input to be converted.
*/
constructor(value: HexInput);
/**
* Serializes the fixed bytes value using the provided serializer.
* This function is essential for converting the fixed bytes into a format suitable for storage or transmission.
*
* @param serializer - The serializer instance used for serialization.
*/
serialize(serializer: Serializer): void;
/**
* Serializes the current instance for an entry function using the provided serializer.
* This allows the instance to be converted into a format suitable for transmission or storage.
*
* @param serializer - The serializer used to perform the serialization.
*/
serializeForEntryFunction(serializer: Serializer): void;
/**
* Serializes the current instance using the provided serializer.
* This function is essential for preparing data to be passed as arguments in script functions.
*
* @param serializer - The serializer instance used to perform the serialization.
*/
serializeForScriptFunction(serializer: Serializer): void;
/**
* Deserializes a fixed-length byte array from the provided deserializer.
* This function helps in reconstructing a FixedBytes object from the serialized data.
*
* @param deserializer - The deserializer instance used to read the byte data.
* @param length - The length of the byte array to be deserialized.
*/
static deserialize(deserializer: Deserializer, length: number): FixedBytes;
}
/**
* This class exists solely to represent a sequence of fixed bytes as a serialized entry function, because
* serializing an entry function appends a prefix that's *only* used for entry function arguments.
*
* NOTE: Using this class for serialized script functions will lead to erroneous and unexpected behavior.
*
* If you wish to convert this class back to a TransactionArgument, you must know the type
* of the argument beforehand, and use the appropriate class to deserialize the bytes within
* an instance of this class.
*/
declare class EntryFunctionBytes extends Serializable implements EntryFunctionArgument {
readonly value: FixedBytes;
/**
* Creates an instance of the class with a specified hexadecimal input value.
*
* @param value - The hexadecimal input to be converted into FixedBytes.
*/
private constructor();
/**
* Serializes the value using the provided serializer.
* This function is essential for accurately representing a sequence of bytes that are already BCS-serialized as a type.
*
* Note that to see the Move, BCS-serialized representation of the underlying fixed byte vector,
* we must not serialize the length prefix.
*
* @param serializer - The serializer instance used to perform the serialization.
*/
serialize(serializer: Serializer): void;
/**
* Serializes the current instance for use as an entry function argument by converting the underlying fixed byte vector to a
* type-agnostic byte vector.
* This process includes serializing the length prefix of the byte vector.
*
* @param serializer - The serializer instance used to perform the serialization.
*/
serializeForEntryFunction(serializer: Serializer): void;
/**
* The only way to create an instance of this class is to use this static method.
* This function should only be used when deserializing a sequence of EntryFunctionPayload arguments.
* @param deserializer - The deserializer instance with the buffered bytes.
* @param length - The length of the bytes to deserialize.
* @returns An instance of this class, which will now only be usable as an EntryFunctionArgument.
*/
static deserialize(deserializer: Deserializer, length: number): EntryFunctionBytes;
}
/**
* Represents a boolean value that can be serialized and deserialized.
* This class extends the Serializable class and provides methods to serialize
* the boolean value for different contexts, such as entry functions and script functions.
*
* @extends Serializable
*/
declare class Bool extends Serializable implements TransactionArgument {
readonly value: boolean;
/**
* Constructs a new instance with a specified value.
* This ensures that the value is validated to be within the acceptable range.
*
* @param value - The number to be validated and assigned, which must be between 0 and MAX_U256_BIG_INT.
*/
constructor(value: boolean);
/**
* Serializes the value using the provided serializer.
* This function is essential for converting the value into a format suitable for transmission or storage.
*
* @param serializer - The serializer instance used to perform the serialization.
*/
serialize(serializer: Serializer): void;
/**
* Serializes the current instance for use in an entry function by converting it to a byte sequence.
* This allows the instance to be properly formatted for serialization in transactions.
*
* @param serializer - The serializer instance used to serialize the byte sequence.
*/
serializeForEntryFunction(serializer: Serializer): void;
/**
* Serializes the current instance for use in a script function.
* This allows for the conversion of the instance into a format suitable for transmission or storage.
*
* @param serializer - The serializer used to perform the serialization.
*/
serializeForScriptFunction(serializer: Serializer): void;
/**
* Deserializes a U256 value from the provided deserializer.
*
* @param deserializer - The deserializer instance used to read the U256 data.
*/
deserialize(deserializer: Deserializer): U256;
static deserialize(deserializer: Deserializer): Bool;
}
/**
* Represents an unsigned 8-bit integer (U8) value.
* This class extends the Serializable class and provides methods for serialization and deserialization of U8 values.
*
* @extends Serializable
*/
declare class U8 extends Serializable implements TransactionArgument {
readonly value: Uint8;
constructor(value: Uint8);
serialize(serializer: Serializer): void;
serializeForEntryFunction(serializer: Serializer): void;
serializeForScriptFunction(serializer: Serializer): void;
static deserialize(deserializer: Deserializer): U8;
}
/**
* Represents a 16-bit unsigned integer (U16) value.
* This class extends the Serializable class and provides methods for serialization
* and deserialization of the U16 value.
*
* @extends Serializable
*/
declare class U16 extends Serializable implements TransactionArgument {
readonly value: Uint16;
constructor(value: Uint16);
serialize(serializer: Serializer): void;
serializeForEntryFunction(serializer: Serializer): void;
serializeForScriptFunction(serializer: Serializer): void;
static deserialize(deserializer: Deserializer): U16;
}
/**
* Represents a 32-bit unsigned integer (U32) that can be serialized and deserialized.
* This class ensures that the value is within the valid range for a U32.
*
* @extends Serializable
*/
declare class U32 extends Serializable implements TransactionArgument {
readonly value: Uint32;
constructor(value: Uint32);
serialize(serializer: Serializer): void;
serializeForEntryFunction(serializer: Serializer): void;
serializeForScriptFunction(serializer: Serializer): void;
static deserialize(deserializer: Deserializer): U32;
}
/**
* Represents a 64-bit unsigned integer (U64) and provides methods for serialization.
*
* This class ensures that the value is within the valid range for a U64 and provides
* functionality to serialize the value for various use cases, including entry functions
* and script functions.
*
* @extends Serializable
*/
declare class U64 extends Serializable implements TransactionArgument {
readonly value: bigint;
constructor(value: AnyNumber);
serialize(serializer: Serializer): void;
serializeForEntryFunction(serializer: Serializer): void;
serializeForScriptFunction(serializer: Serializer): void;
static deserialize(deserializer: Deserializer): U64;
}
/**
* Represents a 128-bit unsigned integer value.
* This class provides methods for serialization and deserialization
* of U128 values, ensuring that the values are within the valid range.
*
* @extends Serializable
*/
declare class U128 extends Serializable implements TransactionArgument {
readonly value: bigint;
constructor(value: AnyNumber);
serialize(serializer: Serializer): void;
serializeForEntryFunction(serializer: Serializer): void;
serializeForScriptFunction(serializer: Serializer): void;
static deserialize(deserializer: Deserializer): U128;
}
/**
* Represents a 256-bit unsigned integer (U256) that extends the Serializable class.
* This class provides methods for serialization and deserialization of U256 values,
* ensuring that the values are within the valid range.
*
* @extends Serializable
*/
declare class U256 extends Serializable implements TransactionArgument {
readonly value: bigint;
constructor(value: AnyNumber);
serialize(serializer: Serializer): void;
serializeForEntryFunction(serializer: Serializer): void;
serializeForScriptFunction(serializer: Serializer): void;
static deserialize(deserializer: Deserializer): U256;
}
/**
* This class is the Aptos Typescript SDK representation of a Move `vector<T>`,
* where `T` represents either a primitive type (`bool`, `u8`, `u64`, ...)
* or a BCS-serializable struct itself.
*
* It is a BCS-serializable, array-like type that contains an array of values of type `T`,
* where `T` is a class that implements `Serializable`.
*
* The purpose of this class is to facilitate easy construction of BCS-serializable
* Move `vector<T>` types.
*
* @example
* // in Move: `vector<u8> [1, 2, 3, 4];`
* const vecOfU8s = new MoveVector<U8>([new U8(1), new U8(2), new U8(3), new U8(4)]);
* // in Move: `std::bcs::to_bytes(vector<u8> [1, 2, 3, 4]);`
* const bcsBytes = vecOfU8s.toUint8Array();
*
* // vector<vector<u8>> [ vector<u8> [1], vector<u8> [1, 2, 3, 4], vector<u8> [5, 6, 7, 8] ];
* const vecOfVecs = new MoveVector<MoveVector<U8>>([
* new MoveVector<U8>([new U8(1)]),
* MoveVector.U8([1, 2, 3, 4]),
* MoveVector.U8([5, 6, 7, 8]),
* ]);
*
* // vector<Option<u8>> [ std::option::some<u8>(1), std::option::some<u8>(2) ];
* const vecOfOptionU8s = new MoveVector<MoveOption<U8>>([
* MoveOption.U8(1),
* MoveOption.U8(2),
* ]);
*
* // vector<MoveString> [ std::string::utf8(b"hello"), std::string::utf8(b"world") ];
* const vecOfStrings = new MoveVector([new MoveString("hello"), new MoveString("world")]);
* const vecOfStrings2 = MoveVector.MoveString(["hello", "world"]);
*
* @param values an Array<T> of values where T is a class that implements Serializable
* @returns a `MoveVector<T>` with the values `values`
*/
declare class MoveVector<T extends Serializable & EntryFunctionArgument> extends Serializable implements TransactionArgument {
values: Array<T>;
/**
* Initializes a new instance of the class with an optional value.
* This constructor sets up the internal vector based on the provided value.
*
* @param values - The initial value to be stored in the vector, or null to initialize an empty vector.
*/
constructor(values: Array<T>);
/**
* Serializes the current instance into a byte sequence suitable for entry functions.
* This allows the data to be properly formatted for transmission or storage.
*
* @param serializer - The serializer instance used to serialize the byte sequence.
*/
serializeForEntryFunction(serializer: Serializer): void;
/**
* NOTE: This function will only work when the inner values in the `MoveVector` are `U8`s.
* @param serializer
*/
/**
* Serialize the string as a fixed byte string without the length prefix for use in a script function.
* @param serializer - The serializer used to convert the byte vector into a format suitable for a script function.
*/
serializeForScriptFunction(serializer: Serializer): void;
/**
* Factory method to generate a MoveVector<U8> from a `number` or `undefined`.
*
* This method allows you to create a MoveVector that encapsulates a U8 value, enabling you to handle optional U8 values
* effectively.
*
* @param values - The values used to fill the MoveVector. If `values` is undefined or null, the resulting MoveVector's
* `.isSome()` method will return false.
* @returns A MoveVector<U8> with an inner value `value`.
*
* @example
* ```typescript
* const v = MoveVector.U8([1, 2, 3, 4]);
* ```
*/
static U8(values: Array<number> | HexInput): MoveVector<U8>;
/**
* Factory method to generate a MoveOption<U16> from a `number` or `null`.
*
* This method allows you to create a MoveVector that can either hold a U16 value or be empty.
*
* @param values - The value used to fill the MoveVector. If `value` is null or undefined, the resulting MoveVector's
* `.isSome()` method will return false.
* @returns A MoveVector<U16> with an inner value `value`.
* @example
* ```typescript
* const v = MoveVector.U16([1, 2, 3, 4]);
* ```
*/
static U16(values: Array<number>): MoveVector<U16>;
/**
* Factory method to generate a MoveVector<U32> from a `number` or `null`.
*
* This method allows you to create a MoveVector that can either hold a U32 value or be empty.
*
* @param values - The value used to fill the MoveVector. If `value` is null or undefined,
* the resulting MoveVector's .isSome() method will return false.
* @returns A MoveVector<U32> with an inner value `value`.
*
* @example
* ```
* const v = MoveVector.U32([1, 2, 3, 4]);
* ```
*/
static U32(values: Array<number>): MoveVector<U32>;
/**
* Factory method to generate a MoveVector<U64> from a number, bigint, or null/undefined.
* This allows for the creation of an optional U64 value that can be checked for presence.
*
* @param values - The value used to fill the MoveVector. If `value` is undefined or null, the resulting MoveVector's
* `.isSome()` method will return false.
* @returns A MoveVector<U64> with an inner value `value`.
*
* @example
* ```typescript
* const v = MoveVector.U64([1, 2, 3, 4]);
* ```
*/
static U64(values: Array<AnyNumber>): MoveVector<U64>;
/**
* Factory method to generate a MoveVector<U128> from a number, bigint, or undefined.
*
* @param values - The value used to fill the MoveVector. If `value` is undefined, the resulting MoveVector's `.isSome()`
* method will return false.
* @returns A MoveVector<U128> with an inner value `value`.
*
* @example
* ```typescript
* const v = MoveVector.U128([1, 2, 3, 4]);
* ```
*/
static U128(values: Array<AnyNumber>): MoveVector<U128>;
/**
* Factory method to generate a MoveVector<U256> from a number, bigint, or null/undefined.
* This allows for the creation of an optional U256 value, enabling checks for presence or absence of a value.
*
* @param values - The value used to fill the MoveVector. If `value` is undefined or null,
* the resulting MoveVector's .isSome() method will return false.
* @returns A MoveVector<U256> with an inner value `value`.
*
* @example
* ```typescript
* const v = MoveVector.U256([1, 2, 3, 4]);
* ```
*/
static U256(values: Array<AnyNumber>): MoveVector<U256>;
/**
* Factory method to generate a MoveVector<Bool> from a `boolean` or `undefined`.
* This method allows you to create an optional boolean value that can be used in various contexts where a boolean may or may
* not be present.
*
* @param values - The value used to fill the MoveVector. If `value` is undefined, the resulting MoveVector's .isSome() method
* will return false.
* @returns A MoveVector<Bool> with an inner value `value`.
*
* @example
* * const v = MoveVector.Bool([true, false, true, false]);
*/
static Bool(values: Array<boolean>): MoveVector<Bool>;
/**
* Factory method to generate a MoveVector<MoveString> from a `string` or `undefined`.
* This function creates a MoveVector that encapsulates a MoveString if the provided value is not null or undefined.
*
* @param values - The value used to fill the MoveVector. If `value` is undefined, the resulting MoveVector's .isSome() method
* will return false.
* @returns A MoveVector<MoveString> with an inner value `value`.
*
* @example
* const v = MoveVector.MoveString(["hello", "world"]);
*/
static MoveString(values: Array<string>): MoveVector<MoveString>;
/**
* Serializes the current object using the provided serializer.
* This function will serialize the value if it is present.
*
* @param serializer - The serializer instance used to perform the serialization.
*/
serialize(serializer: Serializer): void;
/**
* Deserialize a MoveVector of type T, specifically where T is a Serializable and Deserializable type.
*
* NOTE: This only works with a depth of one. Generics will not work.
*
* NOTE: This will not work with types that aren't of the Serializable class.
*
* If you're looking for a more flexible deserialization function, you can use the deserializeVector function
* in the Deserializer class.
*
* @example
* const vec = MoveVector.deserialize(deserializer, U64);
* @param deserializer the Deserializer instance to use, with bytes loaded into it already.
* @param cls the class to typecast the input values to, must be a Serializable and Deserializable type.
* @returns a MoveVector of the corresponding class T
*
*/
static deserialize<T extends Serializable & EntryFunctionArgument>(deserializer: Deserializer, cls: Deserializable<T>): MoveVector<T>;
}
/**
* Represents a serialized data structure that encapsulates a byte array.
* This class extends the Serializable class and provides methods for serialization
* and deserialization of byte data, as well as converting to a MoveVector.
*
* @extends Serializable
*/
declare class Serialized extends Serializable implements TransactionArgument {
readonly value: Uint8Array;
constructor(value: HexInput);
serialize(serializer: Serializer): void;
serializeForEntryFunction(serializer: Serializer): void;
serializeForScriptFunction(serializer: Serializer): void;
static deserialize(deserializer: Deserializer): Serialized;
/**
* Deserialize the bytecode into a MoveVector of the specified type.
* This function allows you to convert serialized data into a usable MoveVector format.
*
* @param cls - The class type of the elements in the MoveVector.
*/
toMoveVector<T extends Serializable & EntryFunctionArgument>(cls: Deserializable<T>): MoveVector<T>;
}
/**
* Represents a string value that can be serialized and deserialized.
* This class extends the Serializable base class and provides methods
* for serializing the string in different contexts, such as for entry
* functions and script functions.
*
* @extends Serializable
*/
declare class MoveString extends Serializable implements TransactionArgument {
value: string;
constructor(value: string);
serialize(serializer: Serializer): void;
serializeForEntryFunction(serializer: Serializer): void;
serializeForScriptFunction(serializer: Serializer): void;
static deserialize(deserializer: Deserializer): MoveString;
}
declare class MoveOption<T extends Serializable & EntryFunctionArgument> extends Serializable implements EntryFunctionArgument {
private vec;
readonly value?: T;
constructor(value?: T | null);
serializeForEntryFunction(serializer: Serializer): void;
/**
* Retrieves the inner value of the MoveOption.
*
* This method is inspired by Rust's `Option<T>.unwrap()`, where attempting to unwrap a `None` value results in a panic.
* This method will throw an error if the value is not present.
*
* @example
* const option = new MoveOption<Bool>(new Bool(true));
* const value = option.unwrap(); // Returns the Bool instance
*
* @throws {Error} Throws an error if the MoveOption does not contain a value.
*
* @returns {T} The contained value if present.
*/
unwrap(): T;
/**
* Check if the MoveOption has a value.
*
* @returns {boolean} Returns true if there is exactly one value in the MoveOption.
*/
isSome(): boolean;
serialize(serializer: Serializer): void;
/**
* Factory method to generate a MoveOption<U8> from a `number` or `undefined`.
*
* @example
* MoveOption.U8(1).isSome() === true;
* MoveOption.U8().isSome() === false;
* MoveOption.U8(undefined).isSome() === false;
* @param value the value used to fill the MoveOption. If `value` is undefined
* the resulting MoveOption's .isSome() method will return false.
* @returns a MoveOption<U8> with an inner value `value`
*/
static U8(value?: number | null): MoveOption<U8>;
/**
* Factory method to generate a MoveOption<U16> from a `number` or `undefined`.
*
* @example
* MoveOption.U16(1).isSome() === true;
* MoveOption.U16().isSome() === false;
* MoveOption.U16(undefined).isSome() === false;
* @param value the value used to fill the MoveOption. If `value` is undefined
* the resulting MoveOption's .isSome() method will return false.
* @returns a MoveOption<U16> with an inner value `value`
*/
static U16(value?: number | null): MoveOption<U16>;
/**
* Factory method to generate a MoveOption<U32> from a `number` or `undefined`.
*
* @example
* MoveOption.U32(1).isSome() === true;
* MoveOption.U32().isSome() === false;
* MoveOption.U32(undefined).isSome() === false;
* @param value the value used to fill the MoveOption. If `value` is undefined
* the resulting MoveOption's .isSome() method will return false.
* @returns a MoveOption<U32> with an inner value `value`
*/
static U32(value?: number | null): MoveOption<U32>;
/**
* Factory method to generate a MoveOption<U64> from a `number` or a `bigint` or `undefined`.
*
* @example
* MoveOption.U64(1).isSome() === true;
* MoveOption.U64().isSome() === false;
* MoveOption.U64(undefined).isSome() === false;
* @param value the value used to fill the MoveOption. If `value` is undefined
* the resulting MoveOption's .isSome() method will return false.
* @returns a MoveOption<U64> with an inner value `value`
*/
static U64(value?: AnyNumber | null): MoveOption<U64>;
/**
* Factory method to generate a MoveOption<U128> from a `number` or a `bigint` or `undefined`.
*
* @example
* MoveOption.U128(1).isSome() === true;
* MoveOption.U128().isSome() === false;
* MoveOption.U128(undefined).isSome() === false;
* @param value the value used to fill the MoveOption. If `value` is undefined
* the resulting MoveOption's .isSome() method will return false.
* @returns a MoveOption<U128> with an inner value `value`
*/
static U128(value?: AnyNumber | null): MoveOption<U128>;
/**
* Factory method to generate a MoveOption<U256> from a `number` or a `bigint` or `undefined`.
*
* @example
* MoveOption.U256(1).isSome() === true;
* MoveOption.U256().isSome() === false;
* MoveOption.U256(undefined).isSome() === false;
* @param value the value used to fill the MoveOption. If `value` is undefined
* the resulting MoveOption's .isSome() method will return false.
* @returns a MoveOption<U256> with an inner value `value`
*/
static U256(value?: AnyNumber | null): MoveOption<U256>;
/**
* Factory method to generate a MoveOption<Bool> from a `boolean` or `undefined`.
*
* @example
* MoveOption.Bool(true).isSome() === true;
* MoveOption.Bool().isSome() === false;
* MoveOption.Bool(undefined).isSome() === false;
* @param value the value used to fill the MoveOption. If `value` is undefined
* the resulting MoveOption's .isSome() method will return false.
* @returns a MoveOption<Bool> with an inner value `value`
*/
static Bool(value?: boolean | null): MoveOption<Bool>;
/**
* Factory method to generate a MoveOption<MoveString> from a `string` or `undefined`.
*
* @example
* MoveOption.MoveString("hello").isSome() === true;
* MoveOption.MoveString("").isSome() === true;
* MoveOption.MoveString().isSome() === false;
* MoveOption.MoveString(undefined).isSome() === false;
* @param value the value used to fill the MoveOption. If `value` is undefined
* the resulting MoveOption's .isSome() method will return false.
* @returns a MoveOption<MoveString> with an inner value `value`
*/
static MoveString(value?: string | null): MoveOption<MoveString>;
static deserialize<U extends Serializable & EntryFunctionArgument>(deserializer: Deserializer, cls: Deserializable<U>): MoveOption<U>;
}
/**
* Represents an authentication key used for account management. Each account stores an authentication key that enables account
* owners to rotate their private key(s) without changing the address that hosts their account. The authentication key is a
* SHA3-256 hash of data and is always 32 bytes in length.
*
* @see {@link https://aptos.dev/concepts/accounts | Account Basics}
*
* Account addresses can be derived from the AuthenticationKey.
*/
declare class AuthenticationKey extends Serializable {
/**
* An authentication key is always a SHA3-256 hash of data, and is always 32 bytes.
*
* The data to hash depends on the underlying public key type and the derivation scheme.
*/
static readonly LENGTH: number;
/**
* The raw bytes of the authentication key.
*/
readonly data: Hex;
/**
* Creates an instance of the AuthenticationKey using the provided hex input.
* This ensures that the hex input is valid and conforms to the required length for an Authentication Key.
*
* @param args - The arguments for constructing the AuthenticationKey.
* @param args.data - The hex input data to be used for the Authentication Key.
* @throws {Error} Throws an error if the length of the provided hex input is not equal to the required Authentication Key
* length.
*/
constructor(args: {
data: HexInput;
});
/**
* Serializes the fixed bytes data into a format suitable for transmission or storage.
*
* @param serializer - The serializer instance used to perform the serialization.
*/
serialize(serializer: Serializer): void;
/**
* Deserialize an AuthenticationKey from the byte buffer in a Deserializer instance.
* @param deserializer - The deserializer to deserialize the AuthenticationKey from.
* @returns An instance of AuthenticationKey.
*/
static deserialize(deserializer: Deserializer): AuthenticationKey;
/**
* Convert the internal data representation to a Uint8Array.
*
* This function is useful for obtaining a byte representation of the data, which can be utilized for serialization or transmission.
*
* @returns Uint8Array representation of the internal data.
*/
toUint8Array(): Uint8Array;
/**
* Generates an AuthenticationKey from the specified scheme and input bytes.
* This function is essential for creating a valid authentication key based on a given scheme.
*
* @param args - The arguments for generating the AuthenticationKey.
* @param args.scheme - The authentication key scheme to use.
* @param args.input - The input data in hexadecimal format to derive the key.
* @returns An instance of AuthenticationKey containing the generated key data.
*/
static fromSchemeAndBytes(args: {
scheme: AuthenticationKeyScheme;
input: HexInput;
}): AuthenticationKey;
/**
* Derives an AuthenticationKey from the provided public key using a specified derivation scheme.
*
* @deprecated Use `fromPublicKey` instead.
* @param args - The arguments for deriving the authentication key.
* @param args.publicKey - The public key used for the derivation.
* @param args.scheme - The scheme to use for deriving the authentication key.
*/
static fromPublicKeyAndScheme(args: {
publicKey: AccountPublicKey;
scheme: AuthenticationKeyScheme;
}): AuthenticationKey;
/**
* Converts a PublicKey to an AuthenticationKey using the derivation scheme inferred from the provided PublicKey instance.
*
* @param args - The arguments for the function.
* @param args.publicKey - The PublicKey to be converted.
* @returns AuthenticationKey - The derived AuthenticationKey.
*/
static fromPublicKey(args: {
publicKey: AccountPublicKey;
}): AuthenticationKey;
/**
* Derives an account address from an AuthenticationKey by translating the AuthenticationKey bytes directly to an AccountAddress.
*
* @returns AccountAddress - The derived account address.
*/
derivedAddress(): AccountAddress;
}
/**
* An abstract representation of a crypto signature,
* associated with a specific signature scheme, e.g., Ed25519 or Secp256k1.
*
* This class represents the product of signing a message directly from a
* PrivateKey and can be verified against a CryptoPublicKey.
*/
declare abstract class Signature extends Serializable {
/**
* Get the raw signature bytes
*/
toUint8Array(): Uint8Array;
/**
* Get the signature as a hex string with a 0x prefix e.g. 0x123456...
* @returns The hex string representation of the signature.
*/
toString(): string;
}
/**
* Represents the arguments required to verify a digital signature.
*
* @param message - The original message that was signed.
* @param signature - The signature to be verified against the message.
*/
interface VerifySignatureArgs {
message: HexInput;
signature: Signature;
}
/**
* Represents an abstract public key.
*
* This class provides a common interface for verifying signatures associated with the public key.
* It allows for the retrieval of the raw public key bytes and the public key in a hexadecimal string format.
*/
declare abstract class PublicKey extends Serializable {
/**
* Verifies that the private key associated with this public key signed the message with the given signature.
* @param args.message The message that was signed
* @param args.signature The signature to verify
*/
abstract verifySignature(args: VerifySignatureArgs): boolean;
/**
* Get the raw public key bytes
*/
toUint8Array(): Uint8Array;
/**
* Get the public key as a hex string with a 0x prefix.
*
* @returns The public key in hex format.
*/
toString(): string;
}
/**
* An abstract representation of an account public key.
*
* Provides a common interface for deriving an authentication key.
*
* @abstract
*/
declare abstract class AccountPublicKey extends PublicKey {
/**
* Get the authentication key associated with this public key
*/
abstract authKey(): AuthenticationKey;
}
/**
* Represents a private key used for signing messages and deriving the associated public key.
*/
interface PrivateKey {
/**
* Sign the given message with the private key to create a signature.
* @param message - The message to be signed, provided in HexInput format.
* @returns A Signature object representing the signed message.
*/
sign(message: HexInput): Signature;
/**
* Derive the public key associated with the private key.
*/
publicKey(): PublicKey;
/**
* Get the private key in bytes (Uint8Array).
*/
toUint8Array(): Uint8Array;
}
declare class PrivateKey {
/**
* The AIP-80 compliant prefixes for each private key type. Append this to a private key's hex representation
* to get an AIP-80 compliant string.
*
* [Read about AIP-80](https://github.com/aptos-foundation/AIPs/blob/main/aips/aip-80.md)
*/
static readonly AIP80_PREFIXES: {
ed25519: string;
secp256k1: string;
};
/**
* Format a HexInput to an AIP-80 compliant string.
*
* [Read about AIP-80](https://github.com/aptos-foundation/AIPs/blob/main/aips/aip-80.md)
*
* @param privateKey - The HexString or Uint8Array format of the private key.
* @param privateKeyType - The private key type
*/
static formatPrivateKey(privateKey: HexInput, type: PrivateKeyVariants): string;
/**
* Parse a HexInput that may be a HexString, Uint8Array, or a AIP-80 compliant string to a Hex instance.
*
* [Read about AIP-80](https://github.com/aptos-foundation/AIPs/blob/main/aips/aip-80.md)
*
* @param value - A HexString, Uint8Array, or a AIP-80 compliant string.
* @param privateKeyType - The private key type
* @param strict - If true, the value MUST be compliant with AIP-80.
*/
static parseHexInput(value: HexInput, type: PrivateKeyVariants, strict?: boolean): Hex;
}
/**
* Checks if an ED25519 signature is non-canonical.
* This function helps determine the validity of a signature by verifying its canonical form.
*
* @param signature - The signature to be checked for canonicality.
* @returns A boolean indicating whether the signature is non-canonical.
*
* Comes from Aptos Core
* https://github.com/aptos-labs/aptos-core/blob/main/crates/aptos-crypto/src/ed25519/ed25519_sigs.rs#L47-L85
*/
declare function isCanonicalEd25519Signature(signature: Signature): boolean;
/**
* Represents the public key of an Ed25519 key pair.
*
* Since [AIP-55](https://github.com/aptos-foundation/AIPs/pull/263) Aptos supports
* `Legacy` and `Unified` authentication keys.
*
* Ed25519 scheme is represented in the SDK as `Legacy authentication key` and also
* as `AnyPublicKey` that represents any `Unified authentication key`.
*/
declare class Ed25519PublicKey extends AccountPublicKey {
/**
* Length of an Ed25519 public key
*/
static readonly LENGTH: number;
/**
* Bytes of the public key
* @private
*/
private readonly key;
/**
* Creates an instance of the Ed25519Signature class from a hex input.
* This constructor validates the length of the signature to ensure it meets the required specifications.
*
* @param hexInput - The hex input representing the Ed25519 signature.
* @throws Error if the signature length is not equal to Ed25519Signature.LENGTH.
*/
constructor(hexInput: HexInput);
/**
* Verifies a signed message using a public key.
*
* @param args - The arguments for verification.
* @param args.message - A signed message as a Hex string or Uint8Array.
* @param args.signature - The signature of the message.
*/
verifySignature(args: VerifySignatureArgs): boolean;
/**
* Generates an authentication key from the public key using the Ed25519 scheme.
* This function is essential for creating a secure authentication key that can be used for further cryptographic operations.
*
* @returns {AuthenticationKey} The generated authentication key.
*/
authKey(): AuthenticationKey;
/**
* Convert the internal data representation to a Uint8Array.
*
* @returns Uint8Array representation of the data.
*/
toUint8Array(): Uint8Array;
/**
* Serializes the data into a byte array using the provided serializer.
* This allows for the conversion of data into a format suitable for transmission or storage.
*
* @param serializer - The serializer instance used to perform the serialization.
*/
serialize(serializer: Serializer): void;
/**
* Deserialize bytes into an Ed25519Signature object.
* This function is used to convert serialized byte data into a usable Ed25519Signature instance.
*
* @param deserializer - The deserializer instance used to read the byte data.
*/
static deserialize(deserializer: Deserializer): Ed25519PublicKey;
/**
* Determine if the provided public key is an instance of Ed25519PublicKey.
*
* @param publicKey - The public key to check.
* @returns True if the public key is an instance of Ed25519PublicKey, otherwise false.
* @deprecated use `instanceof Ed25519PublicKey` instead.
*/
static isPublicKey(publicKey: AccountPublicKey): publicKey is Ed25519PublicKey;
/**
* Determines if the provided public key is a valid Ed25519 public key.
* This function checks for the presence of the "key" property and verifies that its data length matches the expected length
* for Ed25519 public keys.
*
* @param publicKey - The public key to validate.
* @returns A boolean indicating whether the public key is a valid Ed25519 public key.
*/
static isInstance(publicKey: PublicKey): publicKey is Ed25519PublicKey;
}
/**
* Represents the private key of an Ed25519 key pair.
*/
declare class Ed25519PrivateKey extends Serializable implements PrivateKey {
/**
* Length of an Ed25519 private key
* @readonly
*/
static readonly LENGTH: number;
/**
* The Ed25519 key seed to use for BIP-32 compatibility
* See more {@link https://github.com/satoshilabs/slips/blob/master/slip-0010.md}
* @readonly
*/
static readonly SLIP_0010_SEED = "ed25519 seed";
/**
* The Ed25519 signing key
* @private
*/
private readonly signingKey;
/**
* Create a new PrivateKey instance from a Uint8Array or String.
*
* [Read about AIP-80](https://github.com/aptos-foundation/AIPs/blob/main/aips/aip-80.md)
*
* @param hexInput HexInput (string or Uint8Array)
* @param strict If true, private key must AIP-80 compliant.
*/
constructor(hexInput: HexInput, strict?: boolean);
/**
* Generate a new random private key.
*
* @returns Ed25519PrivateKey A newly generated Ed25519 private key.
*/
static generate(): Ed25519PrivateKey;
/**
* Derives a private key from a mnemonic seed phrase using a specified BIP44 path.
* To derive multiple keys from the same phrase, change the path
*
* IMPORTANT: Ed25519 supports hardened derivation only, as it lacks a key homomorphism, making non-hardened derivation impossible.
*
* @param path - The BIP44 path used for key derivation.
* @param mnemonics - The mnemonic seed phrase from which the key will be derived.
* @throws Error if the provided path is not a valid hardened path.
*/
static fromDerivationPath(path: string, mnemonics: string): Ed25519PrivateKey;
/**
* Derives a child private key from a given BIP44 path and seed.
* A private inner function so we can separate from the main fromDerivationPath() method
* to add tests to verify we create the keys correctly.
*
* @param path - The BIP44 path used for key derivation.
* @param seed - The seed phrase created by the mnemonics, represented as a Uint8Array.
* @param offset - The offset used for key derivation, defaults to HARDENED_OFFSET.
* @returns An instance of Ed25519PrivateKey derived from the specified path and seed.
*/
private static fromDerivationPathInner;
/**
* Derive the Ed25519PublicKey for this private key.
*
* @returns Ed25519PublicKey - The derived public key corresponding to the private key.
*/
publicKey(): Ed25519PublicKey;
/**
* Sign the given message with the private key.
* This function generates a digital signature for the specified message, ensuring its authenticity and integrity.
*
* @param message - A message as a string or Uint8Array in HexInput format.
* @returns A digital signature for the provided message.
*/
sign(message: HexInput): Ed25519Signature;
/**
* Get the private key in bytes (Uint8Array).
*
* @returns Uint8Array representation of the private key
*/
toUint8Array(): Uint8Array;
/**
* Get the private key as a hex string with the 0x prefix.
*
* @returns string representation of the private key.
*/
toString(): string;
/**
* Get the private key as a hex string with the 0x prefix.
*
* @returns string representation of the private key.
*/
toHexString(): string;
/**
* Get the private key as a AIP-80 compliant hex string.
*
* [Read about AIP-80](https://github.com/aptos-foundation/AIPs/blob/main/aips/aip-80.md)
*
* @returns AIP-80 compliant string representation of the private key.
*/
toAIP80String(): string;
serialize(serializer: Serializer): void;
static deserialize(deserializer: Deserializer): Ed25519PrivateKey;
/**
* Determines if the provided private key is an instance of Ed25519PrivateKey.
*
* @param privateKey - The private key to check.
* @returns A boolean indicating whether the private key is an Ed25519PrivateKey.
*
* @deprecated Use `instanceof Ed25519PrivateKey` instead.
*/
static isPrivateKey(privateKey: PrivateKey): privateKey is Ed25519PrivateKey;
}
/**
* Represents a signature of a message signed using an Ed25519 private key.
*/
declare class Ed25519Signature extends Signature {
/**
* Length of an Ed25519 signature, which is 64 bytes.
*
* @readonly
*/
static readonly LENGTH = 64;
/**
* The signature bytes
* @private
*/
private readonly data;
constructor(hexInput: HexInput);
toUint8Array(): Uint8Array;
serialize(serializer: Serializer): void;
static deserialize(deserializer: Deserializer): Ed25519Signature;
}
/**
* Contains the derived cryptographic key as a Uint8Array.
*/
type DerivedKeys = {
key: Uint8Array;
chainCode: Uint8Array;
};
/**
* Aptos derive path is 637
*/
declare const APTOS_HARDENED_REGEX: RegExp;
declare const APTOS_BIP44_REGEX: RegExp;
/**
* Supported key types and their associated seeds.
*/
declare enum KeyType {
ED25519 = "ed25519 seed"
}
declare const HARDENED_OFFSET = 2147483648;
/**
* Validate a BIP-44 derivation path string to ensure it meets the required format.
* This function checks if the provided path adheres to the BIP-44 standard for Secp256k1.
* Parse and validate a path that is compliant to BIP-44 in form m/44'/637'/{account_index}'/{change_index}/{address_index}
* for Secp256k1
*
* Note that for Secp256k1, the last two components must be non-hardened.
*
* @param path - The path string to validate (e.g. `m/44'/637'/0'/0/0`).
*/
declare function isValidBIP44Path(path: string): boolean;
/**
* Aptos derive path is 637
*
* Parse and validate a path that is compliant to SLIP-0010 and BIP-44
* in form m/44'/637'/{account_index}'/{change_index}'/{address_index}'.
* See SLIP-0010 {@link https://github.com/satoshilabs/slips/blob/master/slip-0044.md}
* See BIP-44 {@link https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki}
*
* Note that for Ed25519, all components must be hardened.
* This is because non-hardened [PK] derivation would not work due to Ed25519's lack of a key homomorphism.
* Specifically, you cannot derive the PK associated with derivation path a/b/c given the PK of a/b.
* This is because the PK in Ed25519 is, more or less, computed as 𝑔𝐻(𝑠𝑘),
* with the hash function breaking the homomorphism.
*
* @param path - The derivation path string to validate (e.g. `m/44'/637'/0'/0'/0'`).
*/
declare function isValidHardenedPath(path: string): boolean;
declare const deriveKey: (hashSeed: Uint8Array | string, data: Uint8Array | string) => DerivedKeys;
/**
* Derive a child key from the private key
* @param key
* @param chainCode
* @param index
*/
declare const CKDPriv: ({ key, chainCode }: DerivedKeys, index: number) => DerivedKeys;
/**
* Splits derive path into segments
* @param path
*/
declare const splitPath: (path: string) => Array<string>;
/**
* Normalizes the mnemonic by removing extra whitespace and making it lowercase
* @param mnemonic the mnemonic seed phrase
*/
declare const mnemonicToSeed: (mnemonic: string) => Uint8Array;
/**
* Represents the public key of a K-of-N Ed25519 multi-sig transaction.
*
* A K-of-N multi-sig transaction requires at least K out of N authorized signers to sign the transaction
* for it to be executed. This class encapsulates the logic for managing the public keys and the threshold
* for valid signatures.
*
* @see {@link https://aptos.dev/integration/creating-a-signed-transaction/ | Creating a Signed Transaction}
*/
declare class MultiEd25519PublicKey extends AccountPublicKey {
/**
* Maximum number of public keys supported
*/
static readonly MAX_KEYS = 32;
/**
* Minimum number of public keys needed
*/
static readonly MIN_KEYS = 2;
/**
* Minimum threshold for the number of valid signatures required
*/
static readonly MIN_THRESHOLD = 1;
/**
* List of Ed25519 public keys for this LegacyMultiEd25519PublicKey
*/
readonly publicKeys: Ed25519PublicKey[];
/**
* The minimum number of valid signatures required, for the number of public keys specified
*/
readonly threshold: number;
/**
* Public key for a K-of-N multi-sig transaction. A K-of-N multi-sig transaction means that for such a
* transaction to be executed, at least K out of the N authorized signers have signed the transaction
* and passed the check conducted by the chain.
*
* @see {@link
* https://aptos.dev/integration/creating-a-signed-transaction/ | Creating a Signed Transaction}
* @param args - A wrapper to let you choose the param order.
* @param args.publicKeys A list of public keys
* @param args.threshold At least "threshold" signatures must be valid
*/
constructor(args: {
publicKeys: Ed25519PublicKey[];
threshold: number;
});
/**
* Verifies a multi-signature against a given message.
* This function ensures that the provided signatures meet the required threshold and are valid for the given message.
*
* @param args - The arguments for verifying the signature.
* @param args.message - The message that was signed.
* @param args.signature - The multi-signature containing multiple signatures and a bitmap indicating which signatures are valid.
* @returns True if the signature is valid; otherwise, false.
* @throws Error if the bitmap and signatures length mismatch or if there are not enough valid signatures.
*/
verifySignature(args: VerifySignatureArgs): boolean;
/**
* Generates an authentication key based on the current instance's byte representation.
* This function is essential for creating a secure authentication key that can be used for various cryptographic operations.
*
* @returns {AuthenticationKey} The generated authentication key.
*/
authKey(): AuthenticationKey;
/**
* Converts a PublicKeys into Uint8Array (bytes) with: bytes = p1_bytes | ... | pn_bytes | threshold
*/
toUint8Array(): Uint8Array;
/**
* Serializes the current instance into bytes using the provided serializer.
* This allows for the conversion of the instance's data into a format suitable for transmission or storage.
*
* @param serializer - The serializer used to convert the instance into bytes.
*/
serialize(serializer: Serializer): void;
/**
* Deserializes a MultiEd25519Signature from the provided deserializer.
* This function helps in reconstructing a MultiEd25519Signature object from its serialized byte representation.
*
* @param deserializer - The deserializer instance used to read the serialized data.
*/
static deserialize(deserializer: Deserializer): MultiEd25519PublicKey;
}
/**
* Represents the signature of a K-of-N Ed25519 multi-sig transaction.
*
* @see {@link https://aptos.dev/integration/creating-a-signed-transaction/#multisignature-transactions | Creating a Signed Transaction}
*/
declare class MultiEd25519Signature extends Signature {
/**
* Maximum number of Ed25519 signatures supported
*/
static MAX_SIGNATURES_SUPPORTED: number;
/**
* Number of bytes in the bitmap representing who signed the transaction (32-bits)
*/
static BITMAP_LEN: number;
/**
* The list of underlying Ed25519 signatures
*/
readonly signatures: Ed25519Signature[];
/**
* 32-bit Bitmap representing who signed the transaction
*
* This is represented where each public key can be masked to determine whether the message was signed by that key.
*/
readonly bitmap: Uint8Array;
/**
* Signature for a K-of-N multi-sig transaction.
*
* @see {@link
* https://aptos.dev/integration/creating-a-signed-transaction/#multisignature-transactions | Creating a Signed Transaction}
*
* @param args.signatures A list of signatures
* @param args.bitmap 4 bytes, at most 32 signatures are supported. If Nth bit value is `1`, the Nth
* signature should be provided in `signatures`. Bits are read from left to right.
* Alternatively, you can specify an array of bitmap positions.
* Valid position should range between 0 and 31.
* @see MultiEd25519Signature.createBitmap
*/
constructor(args: {
signatures: Ed25519Signature[];
bitmap: Uint8Array | number[];
});
/**
* Converts a MultiSignature into Uint8Array (bytes) with `bytes = s1_bytes | ... | sn_bytes | bitmap`
*/
toUint8Array(): Uint8Array;
serialize(serializer: Serializer): void;
static deserialize(deserializer: Deserializer): MultiEd25519Signature;
/**
* Helper method to create a bitmap out of the specified bit positions.
* This function allows you to set specific bits in a 32-bit long bitmap based on the provided positions.
*
* @param args The arguments for creating the bitmap.
* @param args.bits The bitmap positions that should be set. A position starts at index 0. Valid positions should range between 0 and 31.
*
* @example
* Here's an example of valid `bits`
* ```
* [0, 2, 31]
* ```
* `[0, 2, 31]` means the 1st, 3rd and 32nd bits should be set in the bitmap.
* The result bitmap should be 0b1010000000000000000000000000001
*
* @returns bitmap that is 32 bits long.
*/
static createBitmap(args: {
bits: number[];
}): Uint8Array;
}
/**
* Represents any public key supported by Aptos.
*
* Since [AIP-55](https://github.com/aptos-foundation/AIPs/pull/263) Aptos supports
* `Legacy` and `Unified` authentication keys.
*
* Any unified authentication key is represented in the SDK as `AnyPublicKey`.
*/
declare class AnyPublicKey extends AccountPublicKey {
/**
* Reference to the inner public key
*/
readonly publicKey: PublicKey;
/**
* Index of the underlying enum variant
*/
readonly variant: AnyPublicKeyVariant;
/**
* Creates an instance of the signature class based on the provided signature type.
* This allows for the handling of different signature variants such as Ed25519, Secp256k1, and Keyless.
*
* @param publicKey - The publicKey object which determines the variant to be used.
* @throws Error if the provided signature type is unsupported.
*/
constructor(publicKey: PublicKey);
/**
* Verifies the provided signature against the given message.
* This function helps ensure the integrity and authenticity of the message by confirming that the signature is valid.
*
* @param args - The arguments for signature verification.
* @param args.message - The message that was signed.
* @param args.signature - The signature to verify, which must be an instance of AnySignature.
* @returns A boolean indicating whether the signature is valid for the given message.
*/
verifySignature(args: VerifySignatureArgs): boolean;
/**
* Generates an authentication key from the current instance's byte representation.
* This function is essential for creating a unique identifier for authentication purposes.
*
* @returns {AuthenticationKey} The generated authentication key.
*/
authKey(): AuthenticationKey;
/**
* Get the signature in bytes (Uint8Array).
*
* This function is a warning that it will soon return the underlying signature bytes directly.
* Use AnySignature.bcsToBytes() instead.
*
* @returns Uint8Array representation of the signature.
*/
toUint8Array(): Uint8Array;
/**
* Serializes the current object using the provided serializer.
* This function helps in converting the object into a format suitable for transmission or storage.
*
* @param serializer - The serializer instance used to perform the serialization.
*/
serialize(serializer: Serializer): void;
/**
* Deserializes an AnySignature from the provided deserializer.
* This function helps in reconstructing the AnySignature object from its serialized form, allowing for further processing or validation.
*
* @param deserializer - The deserializer instance used to read the serialized data.
*/
static deserialize(deserializer: Deserializer): AnyPublicKey;
/**
* Determines if the provided public key is an instance of AnyPublicKey.
*
* @param publicKey - The public key to check.
* @deprecated Use `instanceof AnyPublicKey` instead.
*/
static isPublicKey(publicKey: AccountPublicKey): publicKey is AnyPublicKey;
/**
* Determines if the current public key is an instance of Ed25519PublicKey.
*
* @deprecated use `publicKey instanceof Ed25519PublicKey` instead.
*/
isEd25519(): boolean;
/**
* Checks if the public key is an instance of Secp256k1PublicKey.
*
* @deprecated use `publicKey instanceof Secp256k1PublicKey` instead.
*/
isSecp256k1PublicKey(): boolean;
/**
* Determines if the provided publicKey is an instance of a valid PublicKey object.
*
* @param publicKey - The publicKey to be checked for validity.
* @param publicKey.publicKey - The actual publicKey object that needs to be validated.
* @returns True if the signature is a valid instance; otherwise, false.
*/
static isInstance(publicKey: PublicKey): publicKey is AnyPublicKey;
}
/**
* Represents a signature that utilizes the SingleKey authentication scheme.
* This class is designed to encapsulate various types of signatures, which can
* only be generated by a `SingleKeySigner` due to the shared authentication mechanism.
*
* @extends Signature
*/
declare class AnySignature extends Signature {
readonly signature: Signature;
/**
* Index of the underlying enum variant
*/
private readonly variant;
constructor(signature: Signature);
toUint8Array(): Uint8Array;
serialize(serializer: Serializer): void;
static deserialize(deserializer: Deserializer): AnySignature;
static isInstance(signature: Signature): signature is AnySignature;
}
/**
* Represents a multi-key authentication scheme for accounts, allowing multiple public keys
* to be associated with a single account. This class enforces a minimum number of valid signatures
* required to authorize actions, ensuring enhanced security for multi-agent accounts.
*
* The public keys of each individual agent can be any type of public key supported by Aptos.
* Since [AIP-55](https://github.com/aptos-foundation/AIPs/pull/263), Aptos supports
* `Legacy` and `Unified` authentication keys.
*/
declare class MultiKey extends AccountPublicKey {
/**
* List of any public keys
*/
readonly publicKeys: AnyPublicKey[];
/**
* The minimum number of valid signatures required, for the number of public keys specified
*/
readonly signaturesRequired: number;
/**
* Signature for a K-of-N multi-sig transaction.
* This constructor initializes a multi-signature transaction with the provided signatures and bitmap.
*
* @param args An object containing the parameters for the multi-signature transaction.
* @param args.signatures A list of signatures.
* @param args.bitmap A bitmap represented as a Uint8Array or an array of numbers, where each bit indicates whether a
* corresponding signature is present. A maximum of 32 signatures is supported, and the length of the bitmap must be 4 bytes.
*
* @throws Error if the number of signatures exceeds the maximum supported, if the bitmap length is incorrect, or if the number
* of signatures does not match the bitmap.
*/
constructor(args: {
publicKeys: Array<PublicKey>;
signaturesRequired: number;
});
/**
* Verifies the provided signature against the given message.
* This function helps ensure the integrity and authenticity of the message by checking if the signature is valid.
*
* @param args - The arguments for verifying the signature.
* @param args.message - The message that was signed.
* @param args.signature - The signature to verify.
*/
verifySignature(args: VerifySignatureArgs): boolean;
/**
* Generates an authentication key based on the current instance's byte representation.
* This key can be used for secure authentication processes within the system.
*
* @returns {AuthenticationKey} The generated authentication key.
*/
authKey(): AuthenticationKey;
/**
* Serializes the object by writing its signatures and bitmap to the provided serializer.
* This allows the object to be converted into a format suitable for transmission or storage.
*
* @param serializer - The serializer instance used to perform the serialization.
*/
serialize(serializer: Serializer): void;
/**
* Deserializes a MultiKeySignature from the provided deserializer.
* This function retrieves the signatures and bitmap necessary for creating a MultiKeySignature object.
*
* @param deserializer - The deserializer instance used to read the serialized data.
*/
static deserialize(deserializer: Deserializer): MultiKey;
/**
* Create a bitmap that holds the mapping from the original public keys
* to the signatures passed in
*
* @param args.bits array of the index mapping to the matching public keys
* @returns Uint8array bit map
*/
createBitmap(args: {
bits: number[];
}): Uint8Array;
/**
* Get the index of the provided public key.
*
* This function retrieves the index of a specified public key within the MultiKey.
* If the public key does not exist, it throws an error.
*
* @param publicKey - The public key to find the index for.
* @returns The corresponding index of the public key, if it exists.
* @throws Error - If the public key is not found in the MultiKey.
*/
getIndex(publicKey: PublicKey): number;
static isInstance(value: PublicKey): value is MultiKey;
}
/**
* Represents a multi-signature transaction using Ed25519 signatures.
* This class allows for the creation and management of a K-of-N multi-signature scheme,
* where a specified number of signatures are required to authorize a transaction.
*
* It includes functionality to validate the number of signatures against a bitmap,
* which indicates which public keys have signed the transaction.
*/
declare class MultiKeySignature extends Signature {
/**
* Number of bytes in the bitmap representing who signed the transaction (32-bits)
*/
static BITMAP_LEN: number;
/**
* Maximum number of Ed25519 signatures supported
*/
static MAX_SIGNATURES_SUPPORTED: number;
/**
* The list of underlying Ed25519 signatures
*/
readonly signatures: AnySignature[];
/**
* 32-bit Bitmap representing who signed the transaction
*
* This is represented where each public key can be masked to determine whether the message was signed by that key.
*/
readonly bitmap: Uint8Array;
/**
* Signature for a K-of-N multi-sig transaction.
*
* @see {@link
* https://aptos.dev/integration/creating-a-signed-transaction/#multisignature-transactions | Creating a Signed Transaction}
*
* @param args.signatures A list of signatures
* @param args.bitmap 4 bytes, at most 32 signatures are supported. If Nth bit value is `1`, the Nth
* signature should be provided in `signatures`. Bits are read from left to right
*/
constructor(args: {
signatures: Array<Signature | AnySignature>;
bitmap: Uint8Array | number[];
});
/**
* Helper method to create a bitmap out of the specified bit positions
* @param args.bits The bitmap positions that should be set. A position starts at index 0.
* Valid position should range between 0 and 31.
* @example
* Here's an example of valid `bits`
* ```
* [0, 2, 31]
* ```
* `[0, 2, 31]` means the 1st, 3rd and 32nd bits should be set in the bitmap.
* The result bitmap should be 0b1010000000000000000000000000001
*
* @returns bitmap that is 32bit long
*/
static createBitmap(args: {
bits: number[];
}): Uint8Array;
serialize(serializer: Serializer): void;
static deserialize(deserializer: Deserializer): MultiKeySignature;
}
/**
* Represents ephemeral public keys for Aptos Keyless accounts.
*
* These keys are used only temporarily within Keyless accounts and are not utilized as public keys for account identification.
*/
declare class EphemeralPublicKey extends PublicKey {
/**
* The public key itself
*/
readonly publicKey: PublicKey;
/**
* An enum indicating the scheme of the ephemeral public key
*/
readonly variant: EphemeralPublicKeyVariant;
/**
* Creates an instance of EphemeralPublicKey using the provided public key.
* This constructor ensures that only supported signature types are accepted.
*
* @param publicKey - The public key to be used for the ephemeral public key.
* @throws Error if the signature type is unsupported.
*/
constructor(publicKey: PublicKey);
/**
* Verifies a signed message using the ephemeral public key.
*
* @param args - The arguments for the verification.
* @param args.message - The message that was signed.
* @param args.signature - The signature that was signed by the private key of the ephemeral public key.
* @returns true if the signature is valid, otherwise false.
*/
verifySignature(args: {
message: HexInput;
signature: EphemeralSignature;
}): boolean;
/**
* Serializes the current instance, specifically handling the Ed25519 signature type.
* This function ensures that the signature is properly serialized using the provided serializer.
*
* @param serializer - The serializer instance used to serialize the signature.
* @throws Error if the signature type is unknown.
*/
serialize(serializer: Serializer): void;
/**
* Deserializes an EphemeralSignature from the provided deserializer.
* This function allows you to retrieve an EphemeralSignature based on the deserialized data.
*
* @param deserializer - The deserializer instance used to read the serialized data.
*/
static deserialize(deserializer: Deserializer): EphemeralPublicKey;
/**
* Determines if the provided public key is an instance of `EphemeralPublicKey`.
*
* @param publicKey - The public key to check.
* @returns A boolean indicating whether the public key is an ephemeral type.
*/
static isPublicKey(publicKey: PublicKey): publicKey is EphemeralPublicKey;
}
/**
* Represents ephemeral signatures used in Aptos Keyless accounts.
*
* These signatures are utilized within the KeylessSignature framework.
*/
declare class EphemeralSignature extends Signature {
/**
* The signature signed by the private key of an EphemeralKeyPair
*/
readonly signature: Signature;
constructor(signature: Signature);
/**
* Deserializes an ephemeral signature from a hexadecimal input.
* This function allows you to convert a hexadecimal representation of an ephemeral signature into its deserialized form for
* further processing.
*
* @param hexInput - The hexadecimal input representing the ephemeral signature.
*/
static fromHex(hexInput: HexInput): EphemeralSignature;
serialize(serializer: Serializer): void;
static deserialize(deserializer: Deserializer): EphemeralSignature;
}
/**
* An abstract representation of a cryptographic proof associated with specific
* zero-knowledge proof schemes, such as Groth16 and PLONK.
*/
declare abstract class Proof extends Serializable {
}
/**
* The response containing the Groth16 verification key, including the alpha_g1 component.
*/
type Groth16VerificationKeyResponse = {
alpha_g1: string;
beta_g2: string;
delta_g2: string;
gamma_abc_g1: [string, string];
gamma_g2: string;
};
type MoveAnyStruct = {
variant: {
data: string;
type_name: string;
};
};
/**
* Types of API endpoints used for routing requests in the Aptos network.
*/
declare enum AptosApiType {
FULLNODE = "Fullnode",
INDEXER = "Indexer",
FAUCET = "Faucet",
PEPPER = "Pepper",
PROVER = "Prover"
}
/**
* The default max gas amount when none is given.
*
* This is the maximum number of gas units that will be used by a transaction before being rejected.
*
* Note that max gas amount varies based on the transaction. A larger transaction will go over this
* default gas amount, and the value will need to be changed for the specific transaction.
*/
declare const DEFAULT_MAX_GAS_AMOUNT = 200000;
/**
* The default transaction expiration seconds from now.
*
* This time is how long until the blockchain nodes will reject the transaction.
*
* Note that the transaction expiration time varies based on network connection and network load. It may need to be
* increased for the transaction to be processed.
*/
declare const DEFAULT_TXN_EXP_SEC_FROM_NOW = 20;
/**
* The default number of seconds to wait for a transaction to be processed.
*
* This time is the amount of time that the SDK will wait for a transaction to be processed when waiting for
* the results of the transaction. It may take longer based on network connection and network load.
*/
declare const DEFAULT_TXN_TIMEOUT_SEC = 20;
/**
* The default gas currency for the network.
*/
declare const APTOS_COIN = "0x1::aptos_coin::AptosCoin";
declare const APTOS_FA = "0x000000000000000000000000000000000000000000000000000000000000000a";
declare const RAW_TRANSACTION_SALT = "APTOS::RawTransaction";
declare const RAW_TRANSACTION_WITH_DATA_SALT = "APTOS::RawTransactionWithData";
/**
* Supported processor types for the indexer API, sourced from the processor_status table in the indexer database.
* {@link https://cloud.hasura.io/public/graphiql?endpoint=https://api.mainnet.aptoslabs.com/v1/graphql}
*/
declare enum ProcessorType {
ACCOUNT_TRANSACTION_PROCESSOR = "account_transactions_processor",
DEFAULT = "default_processor",
EVENTS_PROCESSOR = "events_processor",
FUNGIBLE_ASSET_PROCESSOR = "fungible_asset_processor",
STAKE_PROCESSOR = "stake_processor",
TOKEN_V2_PROCESSOR = "token_v2_processor",
USER_TRANSACTION_PROCESSOR = "user_transaction_processor",
OBJECT_PROCESSOR = "objects_processor"
}
/**
* Regular expression pattern for Firebase Auth issuer URLs
* Matches URLs in the format: https://securetoken.google.com/[project-id]
* where project-id can contain letters, numbers, hyphens, and underscores
*/
declare const FIREBASE_AUTH_ISS_PATTERN: RegExp;
/**
* Represents the configuration settings for an Aptos SDK client instance.
* This class allows customization of various endpoints and client settings.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* async function runExample() {
* // Create a configuration for connecting to the Aptos testnet
* const config = new AptosConfig({ network: Network.TESTNET });
*
* // Initialize the Aptos client with the configuration
* const aptos = new Aptos(config);
*
* console.log("Aptos client initialized:", aptos);
* }
* runExample().catch(console.error);
* ```
*/
declare class AptosConfig {
/**
* The Network that this SDK is associated with. Defaults to DEVNET
*/
readonly network: Network;
/**
* The client instance the SDK uses. Defaults to `@aptos-labs/aptos-client
*/
readonly client: Client;
/**
* The optional hardcoded fullnode URL to send requests to instead of using the network
*/
readonly fullnode?: string;
/**
* The optional hardcoded faucet URL to send requests to instead of using the network
*/
readonly faucet?: string;
/**
* The optional hardcoded pepper service URL to send requests to instead of using the network
*/
readonly pepper?: string;
/**
* The optional hardcoded prover service URL to send requests to instead of using the network
*/
readonly prover?: string;
/**
* The optional hardcoded indexer URL to send requests to instead of using the network
*/
readonly indexer?: string;
/**
* Optional client configurations
*/
readonly clientConfig?: ClientConfig;
/**
* Optional specific Fullnode configurations
*/
readonly fullnodeConfig?: FullNodeConfig;
/**
* Optional specific Indexer configurations
*/
readonly indexerConfig?: IndexerConfig;
/**
* Optional specific Faucet configurations
*/
readonly faucetConfig?: FaucetConfig;
/**
* Initializes an instance of the Aptos client with the specified settings.
* This allows users to configure various aspects of the client, such as network and endpoints.
*
* @param settings - Optional configuration settings for the Aptos client.
* @param settings.network - The network to connect to, defaults to `Network.DEVNET`.
* @param settings.fullnode - The fullnode endpoint to use for requests.
* @param settings.faucet - The faucet endpoint for obtaining test tokens.
* @param settings.pepper - The pepper used for transaction signing.
* @param settings.prover - The prover endpoint for transaction verification.
* @param settings.indexer - The indexer endpoint for querying blockchain data.
* @param settings.client - Custom client settings, defaults to a standard Aptos client.
* @param settings.clientConfig - Additional configuration for the client.
* @param settings.fullnodeConfig - Additional configuration for the fullnode.
* @param settings.indexerConfig - Additional configuration for the indexer.
* @param settings.faucetConfig - Additional configuration for the faucet.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* async function runExample() {
* // Create a new Aptos client with default settings
* const config = new AptosConfig({ network: Network.TESTNET }); // Specify the network
* const aptos = new Aptos(config);
*
* console.log("Aptos client initialized:", aptos);
* }
* runExample().catch(console.error);
* ```
*/
constructor(settings?: AptosSettings);
/**
* Returns the URL endpoint to send the request to based on the specified API type.
* If a custom URL was provided in the configuration, that URL is returned. Otherwise, the URL endpoint is derived from the network.
*
* @param apiType - The type of Aptos API to get the URL for. This can be one of the following: FULLNODE, FAUCET, INDEXER, PEPPER, PROVER.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network, AptosApiType } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Getting the request URL for the FULLNODE API
* const url = config.getRequestUrl(AptosApiType.FULLNODE);
* console.log("Request URL for FULLNODE:", url);
* }
* runExample().catch(console.error);
* ```
*/
getRequestUrl(apiType: AptosApiType): string;
/**
* Checks if the provided URL is a known pepper service endpoint.
*
* @param url - The URL to check against the known pepper service endpoints.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* const url = "https://example.pepper.service"; // replace with a real pepper service URL
*
* // Check if the URL is a known pepper service endpoint
* const isPepperService = config.isPepperServiceRequest(url);
*
* console.log(`Is the URL a known pepper service? ${isPepperService}`);
* }
* runExample().catch(console.error);
* ```
*/
isPepperServiceRequest(url: string): boolean;
/**
* Checks if the provided URL is a known prover service endpoint.
*
* @param url - The URL to check against known prover service endpoints.
* @returns A boolean indicating whether the URL is a known prover service endpoint.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* // Check if the URL is a known prover service endpoint
* const url = "https://prover.testnet.aptos.dev"; // replace with a real URL if needed
* const isProver = config.isProverServiceRequest(url);
*
* console.log(`Is the URL a known prover service? ${isProver}`);
* ```
*/
isProverServiceRequest(url: string): boolean;
}
declare const EPK_HORIZON_SECS = 10000000;
declare const MAX_AUD_VAL_BYTES = 120;
declare const MAX_UID_KEY_BYTES = 30;
declare const MAX_UID_VAL_BYTES = 330;
declare const MAX_ISS_VAL_BYTES = 120;
declare const MAX_EXTRA_FIELD_BYTES = 350;
declare const MAX_JWT_HEADER_B64_BYTES = 300;
declare const MAX_COMMITED_EPK_BYTES = 93;
/**
* Represents a Keyless Public Key used for authentication.
*
* This class encapsulates the public key functionality for keyless authentication,
* including methods for generating and verifying signatures, as well as serialization
* and deserialization of the key. The KeylessPublicKey is represented in the SDK
* as `AnyPublicKey`.
*/
declare class KeylessPublicKey extends AccountPublicKey {
/**
* The number of bytes that `idCommitment` should be
*/
static readonly ID_COMMITMENT_LENGTH: number;
/**
* The value of the 'iss' claim on the JWT which identifies the OIDC provider.
*/
readonly iss: string;
/**
* A value representing a cryptographic commitment to a user identity.
*
* It is calculated from the aud, uidKey, uidVal, pepper.
*/
readonly idCommitment: Uint8Array;
/**
* Constructs an instance with the specified parameters for cryptographic operations.
*
* @param args - The parameters required to initialize the instance.
* @param args.alphaG1 - The hex representation of the alpha G1 value.
* @param args.betaG2 - The hex representation of the beta G2 value.
* @param args.deltaG2 - The hex representation of the delta G2 value.
* @param args.gammaAbcG1 - An array containing two hex representations for gamma ABC G1 values.
* @param args.gammaG2 - The hex representation of the gamma G2 value.
*/
constructor(iss: string, idCommitment: HexInput);
/**
* Get the authentication key for the keyless public key.
*
* @returns AuthenticationKey - The authentication key derived from the keyless public key.
*/
authKey(): AuthenticationKey;
/**
* Verifies the validity of a signature for a given message.
*
* @param args - The arguments for signature verification.
* @param args.message - The message that was signed.
* @param args.signature - The signature to verify against the message.
* @returns true if the signature is valid; otherwise, false.
*/
verifySignature(args: {
message: HexInput;
signature: KeylessSignature;
}): boolean;
/**
* Serializes the current instance into a format suitable for transmission or storage.
* This function ensures that all relevant fields are properly serialized, including the proof and optional fields.
*
* @param serializer - The serializer instance used to perform the serialization.
* @param serializer.proof - The proof to be serialized.
* @param serializer.expHorizonSecs - The expiration horizon in seconds.
* @param serializer.extraField - An optional additional field for serialization.
* @param serializer.overrideAudVal - An optional override value for auditing.
* @param serializer.trainingWheelsSignature - An optional signature for training wheels.
*/
serialize(serializer: Serializer): void;
/**
* Deserializes a ZeroKnowledgeSig object from the provided deserializer.
* This function allows you to reconstruct a ZeroKnowledgeSig instance from its serialized form.
*
* @param deserializer - The deserializer instance used to read the serialized data.
* @returns A new instance of ZeroKnowledgeSig.
*/
static deserialize(deserializer: Deserializer): KeylessPublicKey;
/**
* Loads a KeylessPublicKey instance from the provided deserializer.
* This function is used to deserialize the necessary components to create a KeylessPublicKey.
*
* @param deserializer - The deserializer used to extract the string and byte data.
* @param deserializer.deserializeStr - A method to deserialize a string value.
* @param deserializer.deserializeBytes - A method to deserialize byte data.
* @returns A new instance of KeylessPublicKey.
*/
static load(deserializer: Deserializer): KeylessPublicKey;
/**
* Determines if the provided public key is an instance of KeylessPublicKey.
*
* @param publicKey - The public key to check.
* @returns A boolean indicating whether the public key is a KeylessPublicKey instance.
*/
static isPublicKey(publicKey: PublicKey): publicKey is KeylessPublicKey;
/**
* Creates a KeylessPublicKey from the JWT components plus pepper
*
* @param args.iss the iss of the identity
* @param args.uidKey the key to use to get the uidVal in the JWT token
* @param args.uidVal the value of the uidKey in the JWT token
* @param args.aud the client ID of the application
* @param args.pepper The pepper used to maintain privacy of the account
* @returns KeylessPublicKey
*/
static create(args: {
iss: string;
uidKey: string;
uidVal: string;
aud: string;
pepper: HexInput;
}): KeylessPublicKey;
/**
* Creates a KeylessPublicKey instance from a JWT and a pepper value.
* This function is useful for generating a public key that can be used for authentication based on the provided JWT claims and pepper.
*
* @param args - The arguments for creating the KeylessPublicKey.
* @param args.jwt - The JSON Web Token to decode.
* @param args.pepper - The pepper value used in the key creation process.
* @param args.uidKey - An optional key to retrieve the unique identifier from the JWT payload, defaults to "sub".
* @returns A KeylessPublicKey instance created from the provided JWT and pepper.
*/
static fromJwtAndPepper(args: {
jwt: string;
pepper: HexInput;
uidKey?: string;
}): KeylessPublicKey;
/**
* Checks if the provided public key is a valid instance by verifying its structure and types.
*
* @param publicKey - The public key to validate.
* @returns A boolean indicating whether the public key is a valid instance.
*/
static isInstance(publicKey: PublicKey): boolean;
}
/**
* Represents a signature of a message signed via a Keyless Account, utilizing proofs or a JWT token for authentication.
*/
declare class KeylessSignature extends Signature {
/**
* The inner signature ZeroKnowledgeSignature or OpenIdSignature
*/
readonly ephemeralCertificate: EphemeralCertificate;
/**
* The jwt header in the token used to create the proof/signature. In json string representation.
*/
readonly jwtHeader: string;
/**
* The expiry timestamp in seconds of the EphemeralKeyPair used to sign
*/
readonly expiryDateSecs: number;
/**
* The ephemeral public key used to verify the signature
*/
readonly ephemeralPublicKey: EphemeralPublicKey;
/**
* The signature resulting from signing with the private key of the EphemeralKeyPair
*/
readonly ephemeralSignature: EphemeralSignature;
constructor(args: {
jwtHeader: string;
ephemeralCertificate: EphemeralCertificate;
expiryDateSecs: number;
ephemeralPublicKey: EphemeralPublicKey;
ephemeralSignature: EphemeralSignature;
});
/**
* Get the kid of the JWT used to derive the Keyless Account used to sign.
*
* @returns the kid as a string
*/
getJwkKid(): string;
serialize(serializer: Serializer): void;
static deserialize(deserializer: Deserializer): KeylessSignature;
static getSimulationSignature(): KeylessSignature;
static isSignature(signature: Signature): signature is KeylessSignature;
}
/**
* Represents an ephemeral certificate containing a signature, specifically a ZeroKnowledgeSig.
* This class can be extended to support additional signature types, such as OpenIdSignature.
*
* @extends Signature
*/
declare class EphemeralCertificate extends Signature {
readonly signature: Signature;
/**
* Index of the underlying enum variant
*/
private readonly variant;
constructor(signature: Signature, variant: EphemeralCertificateVariant);
/**
* Get the public key in bytes (Uint8Array).
*
* @returns Uint8Array representation of the public key
*/
toUint8Array(): Uint8Array;
serialize(serializer: Serializer): void;
static deserialize(deserializer: Deserializer): EphemeralCertificate;
}
/**
* Represents a fixed-size byte array of 32 bytes, extending the Serializable class.
* This class is used for handling and serializing G1 bytes in cryptographic operations.
*
* @extends Serializable
*/
declare class G1Bytes extends Serializable {
data: Uint8Array;
constructor(data: HexInput);
serialize(serializer: Serializer): void;
static deserialize(deserializer: Deserializer): G1Bytes;
}
/**
* Represents a 64-byte G2 element in a cryptographic context.
* This class provides methods for serialization and deserialization of G2 bytes.
*
* @extends Serializable
*/
declare class G2Bytes extends Serializable {
data: Uint8Array;
constructor(data: HexInput);
serialize(serializer: Serializer): void;
static deserialize(deserializer: Deserializer): G2Bytes;
}
/**
* Represents a Groth16 zero-knowledge proof, consisting of three proof points in compressed serialization format.
* The points are the compressed serialization of affine representation of the proof.
*
* @extends Proof
*/
declare class Groth16Zkp extends Proof {
/**
* The bytes of G1 proof point a
*/
a: G1Bytes;
/**
* The bytes of G2 proof point b
*/
b: G2Bytes;
/**
* The bytes of G1 proof point c
*/
c: G1Bytes;
constructor(args: {
a: HexInput;
b: HexInput;
c: HexInput;
});
serialize(serializer: Serializer): void;
static deserialize(deserializer: Deserializer): Groth16Zkp;
}
/**
* Represents a container for different types of zero-knowledge proofs.
*
* @extends Serializable
*/
declare class ZkProof extends Serializable {
readonly proof: Proof;
/**
* Index of the underlying enum variant
*/
private readonly variant;
constructor(proof: Proof, variant: ZkpVariant);
serialize(serializer: Serializer): void;
static deserialize(deserializer: Deserializer): ZkProof;
}
/**
* Represents a zero-knowledge signature, encapsulating the proof and its associated metadata.
*
* @extends Signature
*/
declare class ZeroKnowledgeSig extends Signature {
/**
* The proof
*/
readonly proof: ZkProof;
/**
* The max lifespan of the proof
*/
readonly expHorizonSecs: number;
/**
* A key value pair on the JWT token that can be specified on the signature which would reveal the value on chain.
* Can be used to assert identity or other attributes.
*/
readonly extraField?: string;
/**
* The 'aud' value of the recovery service which is set when recovering an account.
*/
readonly overrideAudVal?: string;
/**
* The training wheels signature
*/
readonly trainingWheelsSignature?: EphemeralSignature;
constructor(args: {
proof: ZkProof;
expHorizonSecs: number;
extraField?: string;
overrideAudVal?: string;
trainingWheelsSignature?: EphemeralSignature;
});
/**
* Deserialize a ZeroKnowledgeSig object from its BCS serialization in bytes.
*
* @param bytes - The bytes representing the serialized ZeroKnowledgeSig.
* @returns ZeroKnowledgeSig - The deserialized ZeroKnowledgeSig object.
*/
static fromBytes(bytes: Uint8Array): ZeroKnowledgeSig;
serialize(serializer: Serializer): void;
static deserialize(deserializer: Deserializer): ZeroKnowledgeSig;
}
/**
* Represents the on-chain configuration for how Keyless accounts operate.
*
* @remarks
* This class encapsulates the verification key and the maximum lifespan of ephemeral key pairs,
* which are essential for the functionality of Keyless accounts.
*/
declare class KeylessConfiguration {
/**
* The verification key used to verify Groth16 proofs on chain
*/
readonly verificationKey: Groth16VerificationKey;
/**
* The maximum lifespan of an ephemeral key pair. This is configured on chain.
*/
readonly maxExpHorizonSecs: number;
constructor(verificationKey: Groth16VerificationKey, maxExpHorizonSecs: number);
static create(res: Groth16VerificationKeyResponse, maxExpHorizonSecs: number): KeylessConfiguration;
}
/**
* Represents the verification key stored on-chain used to verify Groth16 proofs.
*/
declare class Groth16VerificationKey {
/**
* The `alpha * G`, where `G` is the generator of G1
*/
readonly alphaG1: G1Bytes;
/**
* The `alpha * H`, where `H` is the generator of G2
*/
readonly betaG2: G2Bytes;
/**
* The `delta * H`, where `H` is the generator of G2
*/
readonly deltaG2: G2Bytes;
/**
* The `gamma^{-1} * (beta * a_i + alpha * b_i + c_i) * H`, where H is the generator of G1
*/
readonly gammaAbcG1: [G1Bytes, G1Bytes];
/**
* The `gamma * H`, where `H` is the generator of G2
*/
readonly gammaG2: G2Bytes;
constructor(args: {
alphaG1: HexInput;
betaG2: HexInput;
deltaG2: HexInput;
gammaAbcG1: [HexInput, HexInput];
gammaG2: HexInput;
});
/**
* Calculates the hash of the serialized form of the verification key.
* This is useful for comparing verification keys or using them as unique identifiers.
*
* @returns The SHA3-256 hash of the serialized verification key as a Uint8Array
*/
hash(): Uint8Array;
serialize(serializer: Serializer): void;
/**
* Converts a Groth16VerificationKeyResponse object into a Groth16VerificationKey instance.
*
* @param res - The Groth16VerificationKeyResponse object containing the verification key data.
* @param res.alpha_g1 - The alpha G1 value from the response.
* @param res.beta_g2 - The beta G2 value from the response.
* @param res.delta_g2 - The delta G2 value from the response.
* @param res.gamma_abc_g1 - The gamma ABC G1 value from the response.
* @param res.gamma_g2 - The gamma G2 value from the response.
* @returns A Groth16VerificationKey instance constructed from the provided response data.
*/
static fromGroth16VerificationKeyResponse(res: Groth16VerificationKeyResponse): Groth16VerificationKey;
}
/**
* Retrieves the configuration parameters for Keyless Accounts on the blockchain, including the verifying key and the maximum
* expiry horizon.
*
* @param args - The arguments for retrieving the keyless configuration.
* @param args.aptosConfig - The Aptos configuration object containing network details.
* @param args.options - Optional parameters for the request.
* @param args.options.ledgerVersion - The ledger version to query; if not provided, the latest version will be used.
* @returns KeylessConfiguration - The configuration object containing the verifying key and maximum expiry horizon.
*/
declare function getKeylessConfig(args: {
aptosConfig: AptosConfig;
options?: LedgerVersionArg;
}): Promise<KeylessConfiguration>;
/**
* Parses a JWT and returns the 'iss', 'aud', and 'uid' values.
*
* @param args - The arguments for parsing the JWT.
* @param args.jwt - The JWT to parse.
* @param args.uidKey - The key to use for the 'uid' value; defaults to 'sub'.
* @returns The 'iss', 'aud', and 'uid' values from the JWT.
*/
declare function getIssAudAndUidVal(args: {
jwt: string;
uidKey?: string;
}): {
iss: string;
aud: string;
uidVal: string;
};
declare function getKeylessJWKs(args: {
aptosConfig: AptosConfig;
jwkAddr?: AccountAddressInput;
options?: LedgerVersionArg;
}): Promise<Map<string, MoveJWK[]>>;
declare class MoveJWK extends Serializable {
kid: string;
kty: string;
alg: string;
e: string;
n: string;
constructor(args: {
kid: string;
kty: string;
alg: string;
e: string;
n: string;
});
serialize(serializer: Serializer): void;
static fromMoveStruct(struct: MoveAnyStruct): MoveJWK;
static deserialize(deserializer: Deserializer): MoveJWK;
}
interface JwtHeader {
kid: string;
}
/**
* Safely parses the JWT header.
* @param jwtHeader The JWT header string
* @returns Parsed JWT header as an object.
*/
declare function parseJwtHeader(jwtHeader: string): JwtHeader;
/**
* Represents the FederatedKeylessPublicKey public key
*
* These keys use an on-chain address as a source of truth for the JWK used to verify signatures.
*
* FederatedKeylessPublicKey authentication key is represented in the SDK as `AnyPublicKey`.
*/
declare class FederatedKeylessPublicKey extends AccountPublicKey {
/**
* The address that contains the JWK set to be used for verification.
*/
readonly jwkAddress: AccountAddress;
/**
* The inner public key which contains the standard Keyless public key.
*/
readonly keylessPublicKey: KeylessPublicKey;
constructor(jwkAddress: AccountAddressInput, keylessPublicKey: KeylessPublicKey);
/**
* Get the authentication key for the federated keyless public key
*
* @returns AuthenticationKey
*/
authKey(): AuthenticationKey;
/**
* Verifies a signed data with a public key
*
* @param args.message message
* @param args.signature The signature
* @returns true if the signature is valid
*/
verifySignature(args: {
message: HexInput;
signature: KeylessSignature;
}): boolean;
serialize(serializer: Serializer): void;
static deserialize(deserializer: Deserializer): FederatedKeylessPublicKey;
static isPublicKey(publicKey: PublicKey): publicKey is FederatedKeylessPublicKey;
/**
* Creates a FederatedKeylessPublicKey from the JWT components plus pepper
*
* @param args.iss the iss of the identity
* @param args.uidKey the key to use to get the uidVal in the JWT token
* @param args.uidVal the value of the uidKey in the JWT token
* @param args.aud the client ID of the application
* @param args.pepper The pepper used to maintain privacy of the account
* @returns FederatedKeylessPublicKey
*/
static create(args: {
iss: string;
uidKey: string;
uidVal: string;
aud: string;
pepper: HexInput;
jwkAddress: AccountAddressInput;
}): FederatedKeylessPublicKey;
static fromJwtAndPepper(args: {
jwt: string;
pepper: HexInput;
jwkAddress: AccountAddressInput;
uidKey?: string;
}): FederatedKeylessPublicKey;
static isInstance(publicKey: PublicKey): boolean;
}
/**
* Hashes a string to a field element via Poseidon hashing.
* This function is useful for converting a string into a fixed-size hash that can be used in cryptographic applications.
*
* @param str - The string to be hashed.
* @param maxSizeBytes - The maximum size in bytes for the resulting hash.
* @returns bigint - The result of the hash.
*/
declare function hashStrToField(str: string, maxSizeBytes: number): bigint;
/**
* Pads and packs the given byte array to a specified maximum size and appends its length.
* This function ensures that the byte array does not exceed the maximum size, throwing an error if it does.
* It is useful for preparing byte data for further processing or transmission by ensuring a consistent format.
*
* @param bytes - The byte array to be padded and packed.
* @param maxSizeBytes - The maximum allowed size for the byte array.
* @throws Error if the length of the input bytes exceeds the maximum size.
* @returns A new Uint8Array that contains the padded and packed bytes along with the length of the original byte array.
*/
declare function padAndPackBytesWithLen(bytes: Uint8Array, maxSizeBytes: number): bigint[];
/**
* Converts a little-endian byte array into a BigInt.
* This function is useful for interpreting byte data as a numerical value in a way that respects the little-endian format.
*
* @param bytes - The byte array to convert.
* @returns The resulting BigInt representation of the byte array.
*/
declare function bytesToBigIntLE(bytes: Uint8Array): bigint;
/**
* Converts a bigint value into a little-endian byte array of a specified length.
* This function is useful for representing large integers in a byte format, which is often required for cryptographic operations
* or binary data manipulation.
*
* @param value - The number to convert into bytes.
* @param length - The desired length of the resulting byte array.
* @returns A Uint8Array containing the little-endian representation of the bigint value.
*/
declare function bigIntToBytesLE(value: bigint | number, length: number): Uint8Array;
/**
* Hashes up to 16 scalar elements via the Poseidon hashing algorithm.
* Each element must be scalar fields of the BN254 elliptic curve group.
*
* @param inputs - An array of elements to be hashed, which can be of type number, bigint, or string.
* @returns bigint - The result of the hash.
* @throws Error - Throws an error if the input length exceeds the maximum allowed.
*/
declare function poseidonHash(inputs: (number | bigint | string)[]): bigint;
/**
* Represents a Secp256k1 ECDSA public key.
*
* @extends PublicKey
* @property LENGTH - The length of the Secp256k1 public key in bytes.
*/
declare class Secp256k1PublicKey extends PublicKey {
static readonly LENGTH: number;
static readonly COMPRESSED_LENGTH: number;
private readonly key;
/**
* Create a new PublicKey instance from a HexInput, which can be a string or Uint8Array.
* This constructor validates the length of the provided signature data.
*
* @param hexInput - A HexInput (string or Uint8Array) representing the signature data.
* @throws Error if the length of the signature data is not equal to Secp256k1Signature.LENGTH.
*/
constructor(hexInput: HexInput);
/**
* Verifies a Secp256k1 signature against the public key.
*
* This function checks the validity of a signature for a given message, ensuring that the signature is canonical as a malleability check.
*
* @param args - The arguments for verifying the signature.
* @param args.message - The message that was signed.
* @param args.signature - The signature to verify against the public key.
*/
verifySignature(args: VerifySignatureArgs): boolean;
/**
* Get the data as a Uint8Array representation.
*
* @returns Uint8Array representation of the data.
*/
toUint8Array(): Uint8Array;
/**
* Serializes the data into a byte array using the provided serializer.
* This function is essential for converting data into a format suitable for transmission or storage.
*
* @param serializer - The serializer instance used to convert the data.
*/
serialize(serializer: Serializer): void;
/**
* Deserializes a Secp256k1Signature from the provided deserializer.
* This function allows you to reconstruct a Secp256k1Signature object from its serialized byte representation.
*
* @param deserializer - The deserializer instance used to read the serialized data.
*/
deserialize(deserializer: Deserializer): Secp256k1Signature;
static deserialize(deserializer: Deserializer): Secp256k1PublicKey;
/**
* Determine if the provided public key is an instance of Secp256k1PublicKey.
*
* @deprecated use `instanceof Secp256k1PublicKey` instead
* @param publicKey - The public key to check.
*/
static isPublicKey(publicKey: PublicKey): publicKey is Secp256k1PublicKey;
/**
* Determines if the provided public key is a valid instance of a Secp256k1 public key.
* This function checks for the presence of a "key" property and validates the length of the key data.
*
* @param publicKey - The public key to validate.
* @returns A boolean indicating whether the public key is a valid Secp256k1 public key.
*/
static isInstance(publicKey: PublicKey): publicKey is Secp256k1PublicKey;
}
/**
* Represents a Secp256k1 ECDSA private key, providing functionality to create, sign messages,
* derive public keys, and serialize/deserialize the key.
*/
declare class Secp256k1PrivateKey extends Serializable implements PrivateKey {
/**
* Length of Secp256k1 ecdsa private key
*/
static readonly LENGTH: number;
/**
* The private key bytes
* @private
*/
private readonly key;
/**
* Create a new PrivateKey instance from a Uint8Array or String.
*
* [Read about AIP-80](https://github.com/aptos-foundation/AIPs/blob/main/aips/aip-80.md)
*
* @param hexInput A HexInput (string or Uint8Array)
* @param strict If true, private key must AIP-80 compliant.
*/
constructor(hexInput: HexInput, strict?: boolean);
/**
* Generate a new random private key.
*
* @returns Secp256k1PrivateKey - A newly generated Secp256k1 private key.
*/
static generate(): Secp256k1PrivateKey;
/**
* Derives a private key from a mnemonic seed phrase using a specified BIP44 path.
*
* @param path - The BIP44 path to derive the key from.
* @param mnemonics - The mnemonic seed phrase used for key generation.
*
* @returns The generated private key.
*
* @throws Error if the provided path is not a valid BIP44 path.
*/
static fromDerivationPath(path: string, mnemonics: string): Secp256k1PrivateKey;
/**
* Derives a private key from a specified BIP44 path using a given seed.
* This function is essential for generating keys that follow the hierarchical deterministic (HD) wallet structure.
*
* @param path - The BIP44 path used for key derivation.
* @param seed - The seed phrase created by the mnemonics, represented as a Uint8Array.
* @returns The generated private key as an instance of Secp256k1PrivateKey.
* @throws Error if the derived private key is invalid.
*/
private static fromDerivationPathInner;
/**
* Sign the given message with the private key.
* This function generates a cryptographic signature for the provided message, ensuring the signature is canonical and non-malleable.
*
* @param message - A message in HexInput format to be signed.
* @returns Signature - The generated signature for the provided message.
*/
sign(message: HexInput): Secp256k1Signature;
/**
* Derive the Secp256k1PublicKey from this private key.
*
* @returns Secp256k1PublicKey The derived public key.
*/
publicKey(): Secp256k1PublicKey;
/**
* Get the private key in bytes (Uint8Array).
*
* @returns
*/
toUint8Array(): Uint8Array;
/**
* Get the private key as a string representation.
*
* @returns string representation of the private key
*/
toString(): string;
/**
* Get the private key as a hex string with the 0x prefix.
*
* @returns string representation of the private key.
*/
toHexString(): string;
/**
* Get the private key as a AIP-80 compliant hex string.
*
* [Read about AIP-80](https://github.com/aptos-foundation/AIPs/blob/main/aips/aip-80.md)
*
* @returns AIP-80 compliant string representation of the private key.
*/
toAIP80String(): string;
serialize(serializer: Serializer): void;
static deserialize(deserializer: Deserializer): Secp256k1PrivateKey;
/**
* Determines if the provided private key is an instance of Secp256k1PrivateKey.
*
* @param privateKey - The private key to be checked.
*
* @deprecated use `instanceof Secp256k1PrivateKey` instead
*/
static isPrivateKey(privateKey: PrivateKey): privateKey is Secp256k1PrivateKey;
}
/**
* Represents a signature of a message signed using a Secp256k1 ECDSA private key.
*
*/
declare class Secp256k1Signature extends Signature {
/**
* Secp256k1 ecdsa signatures are 256-bit or 64 bytes
* @readonly
*/
static readonly LENGTH = 64;
/**
* The signature bytes
* @private
*/
private readonly data;
/**
* Create a new Signature instance from a Uint8Array or String.
*
* @param hexInput A HexInput (string or Uint8Array)
*/
constructor(hexInput: HexInput);
toUint8Array(): Uint8Array;
serialize(serializer: Serializer): void;
static deserialize(deserializer: Deserializer): Secp256k1Signature;
}
/**
* Represents an account authenticator that can handle multiple authentication variants.
* This class serves as a base for different types of account authenticators, allowing for serialization
* and deserialization of various authenticator types.
*
* @extends Serializable
*/
declare abstract class AccountAuthenticator extends Serializable {
abstract serialize(serializer: Serializer): void;
/**
* Deserializes an AccountAuthenticator from the provided deserializer.
* This function helps in reconstructing the AccountAuthenticator object based on the variant index.
*
* @param deserializer - The deserializer instance used to read the serialized data.
*/
static deserialize(deserializer: Deserializer): AccountAuthenticator;
/**
* Determines if the current instance is an Ed25519 account authenticator.
*
* @returns {boolean} True if the instance is of type AccountAuthenticatorEd25519, otherwise false.
*/
isEd25519(): this is AccountAuthenticatorEd25519;
/**
* Determines if the current instance is of type AccountAuthenticatorMultiEd25519.
*
* @returns {boolean} True if the instance is a multi-signature Ed25519 account authenticator, otherwise false.
*/
isMultiEd25519(): this is AccountAuthenticatorMultiEd25519;
/**
* Determines if the current instance is of the type AccountAuthenticatorSingleKey.
*
* @returns {boolean} True if the instance is an AccountAuthenticatorSingleKey, otherwise false.
*/
isSingleKey(): this is AccountAuthenticatorSingleKey;
/**
* Determine if the current instance is of type AccountAuthenticatorMultiKey.
*
* @returns {boolean} Returns true if the instance is an AccountAuthenticatorMultiKey, otherwise false.
*/
isMultiKey(): this is AccountAuthenticatorMultiKey;
}
/**
* Represents an Ed25519 transaction authenticator for multi-signer transactions.
* This class encapsulates the account's Ed25519 public key and signature.
*
* @param public_key - The Ed25519 public key associated with the account.
* @param signature - The Ed25519 signature for the account.
*/
declare class AccountAuthenticatorEd25519 extends AccountAuthenticator {
readonly public_key: Ed25519PublicKey;
readonly signature: Ed25519Signature;
/**
* Creates an instance of the class with the specified public keys and signatures.
*
* @param public_key The public key used for verification.
* @param signature The signatures corresponding to the public keys.
*/
constructor(public_key: Ed25519PublicKey, signature: Ed25519Signature);
/**
* Serializes the account authenticator data into the provided serializer.
* This function captures the multi-key variant, public keys, and signatures for serialization.
*
* @param serializer - The serializer instance used to perform the serialization.
*/
serialize(serializer: Serializer): void;
/**
* Loads an instance of AccountAuthenticatorMultiKey from the provided deserializer.
* This function helps in reconstructing the authenticator object using the deserialized public keys and signatures.
*
* @param deserializer - The deserializer used to extract the necessary data for loading the authenticator.
*/
static load(deserializer: Deserializer): AccountAuthenticatorEd25519;
}
/**
* Represents a transaction authenticator for Multi Ed25519, designed for multi-signer transactions.
*
* @param public_key - The MultiEd25519 public key of the account.
* @param signature - The MultiEd25519 signature of the account.
*/
declare class AccountAuthenticatorMultiEd25519 extends AccountAuthenticator {
readonly public_key: MultiEd25519PublicKey;
readonly signature: MultiEd25519Signature;
constructor(public_key: MultiEd25519PublicKey, signature: MultiEd25519Signature);
serialize(serializer: Serializer): void;
static load(deserializer: Deserializer): AccountAuthenticatorMultiEd25519;
}
/**
* Represents an account authenticator that utilizes a single key for signing.
* This class is designed to handle authentication using a public key and its corresponding signature.
*
* @param public_key - The public key used for authentication.
* @param signature - The signature associated with the public key.
*/
declare class AccountAuthenticatorSingleKey extends AccountAuthenticator {
readonly public_key: AnyPublicKey;
readonly signature: AnySignature;
constructor(public_key: AnyPublicKey, signature: AnySignature);
serialize(serializer: Serializer): void;
static load(deserializer: Deserializer): AccountAuthenticatorSingleKey;
}
/**
* Represents an account authenticator that supports multiple keys and signatures for multi-signature scenarios.
*
* @param public_keys - The public keys used for authentication.
* @param signatures - The signatures corresponding to the public keys.
*/
declare class AccountAuthenticatorMultiKey extends AccountAuthenticator {
readonly public_keys: MultiKey;
readonly signatures: MultiKeySignature;
constructor(public_keys: MultiKey, signatures: MultiKeySignature);
serialize(serializer: Serializer): void;
static load(deserializer: Deserializer): AccountAuthenticatorMultiKey;
}
/**
* AccountAuthenticatorNoAccountAuthenticator for no account authenticator
* It represents the absence of a public key for transaction simulation.
* It allows skipping the public/auth key check during the simulation.
*/
declare class AccountAuthenticatorNoAccountAuthenticator extends AccountAuthenticator {
serialize(serializer: Serializer): void;
static load(deserializer: Deserializer): AccountAuthenticatorNoAccountAuthenticator;
}
/**
* Creates an object address from creator address and seed
*
* @param creatorAddress The object creator account address
* @param seed The seed in either Uint8Array | string type
*
* @returns The object account address
*/
declare const createObjectAddress: (creatorAddress: AccountAddress, seed: Uint8Array | string) => AccountAddress;
/**
* Creates a resource address from creator address and seed
*
* @param creatorAddress The creator account address
* @param seed The seed in either Uint8Array | string type
*
* @returns The resource account address
*/
declare const createResourceAddress: (creatorAddress: AccountAddress, seed: Uint8Array | string) => AccountAddress;
/**
* Creates a token object address from creator address, collection name and token name
*
* @param creatorAddress The token creator account address
* @param collectionName The collection name
* @param tokenName The token name
*
* @returns The token account address
*/
declare const createTokenAddress: (creatorAddress: AccountAddress, collectionName: string, tokenName: string) => AccountAddress;
/**
* Represents a ChainId that can be serialized and deserialized.
*
* @extends Serializable
*/
declare class ChainId extends Serializable {
readonly chainId: number;
/**
* Initializes a new instance of the class with the specified chain ID.
*
* @param chainId - The ID of the blockchain network to be used.
*/
constructor(chainId: number);
/**
* Serializes the current object using the provided serializer.
* This function helps in converting the object into a format suitable for transmission or storage.
*
* @param serializer - The serializer instance used to perform the serialization.
*/
serialize(serializer: Serializer): void;
/**
* Deserializes a ChainId from the provided deserializer.
* This function allows you to reconstruct a ChainId object from serialized data.
*
* @param deserializer - The deserializer instance used to read the serialized data.
*/
static deserialize(deserializer: Deserializer): ChainId;
}
/**
* Represents an Identifier that can be serialized and deserialized.
* This class is used to denote the module "name" in "ModuleId" and
* the "function name" in "EntryFunction".
*
* @extends Serializable
*/
declare class Identifier extends Serializable {
identifier: string;
/**
* Creates an instance of the class with a specified identifier.
*
* @param identifier - The unique identifier for the instance.
*/
constructor(identifier: string);
/**
* Serializes the identifier of the current instance using the provided serializer.
*
* @param serializer - The serializer instance used to perform the serialization.
*/
serialize(serializer: Serializer): void;
/**
* Deserializes an identifier from the provided deserializer.
* This function is useful for reconstructing an Identifier object from a serialized format.
*
* @param deserializer - The deserializer instance used to read the serialized data.
*/
static deserialize(deserializer: Deserializer): Identifier;
}
/**
* Represents a ModuleId that can be serialized and deserialized.
* A ModuleId consists of a module address (e.g., "0x1") and a module name (e.g., "coin").
*/
declare class ModuleId extends Serializable {
readonly address: AccountAddress;
readonly name: Identifier;
/**
* Initializes a new instance of the module with the specified account address and name.
*
* @param address - The account address, e.g., "0x1".
* @param name - The module name under the specified address, e.g., "coin".
*/
constructor(address: AccountAddress, name: Identifier);
/**
* Converts a string literal in the format "account_address::module_name" to a ModuleId.
* @param moduleId - A string literal representing the module identifier.
* @throws Error if the provided moduleId is not in the correct format.
* @returns ModuleId - The corresponding ModuleId object.
*/
static fromStr(moduleId: MoveModuleId): ModuleId;
/**
* Serializes the address and name properties using the provided serializer.
* This function is essential for converting the object's data into a format suitable for transmission or storage.
*
* @param serializer - The serializer instance used to perform the serialization.
*/
serialize(serializer: Serializer): void;
/**
* Deserializes a ModuleId from the provided deserializer.
* This function retrieves the account address and identifier to construct a ModuleId instance.
*
* @param deserializer - The deserializer instance used to read the data.
*/
static deserialize(deserializer: Deserializer): ModuleId;
}
/**
* Represents a type tag in the serialization framework, serving as a base class for various specific type tags.
* This class provides methods for serialization and deserialization of type tags, as well as type checking methods
* to determine the specific type of the tag at runtime.
*
* @extends Serializable
*/
declare abstract class TypeTag extends Serializable {
abstract serialize(serializer: Serializer): void;
/**
* Deserializes a StructTag from the provided deserializer.
* This function allows you to reconstruct a StructTag object from its serialized form.
*
* @param deserializer - The deserializer instance used to read the serialized data.
*/
deserialize(deserializer: Deserializer): StructTag;
static deserialize(deserializer: Deserializer): TypeTag;
abstract toString(): string;
/**
* Determines if the current instance is of type TypeTagBool.
*
* @returns {boolean} True if the instance is a TypeTagBool, otherwise false.
*/
isBool(): this is TypeTagBool;
/**
* Determines if the current instance is of type TypeTagAddress.
*
* @returns {boolean} True if the instance is a TypeTagAddress, otherwise false.
*/
isAddress(): this is TypeTagAddress;
/**
* Determines if the current instance is of type TypeTagGeneric.
*
* @returns {boolean} Returns true if the instance is a TypeTagGeneric, otherwise false.
*/
isGeneric(): this is TypeTagGeneric;
/**
* Determine if the current instance is a TypeTagSigner.
*
* @returns {boolean} Returns true if the instance is a TypeTagSigner, otherwise false.
*/
isSigner(): this is TypeTagSigner;
/**
* Checks if the current instance is a vector type.
* This can help determine the specific type of data structure being used.
*
* @returns {boolean} True if the instance is of type TypeTagVector, otherwise false.
*/
isVector(): this is TypeTagVector;
/**
* Determines if the current instance is a structure type.
*
* @returns {boolean} True if the instance is of type TypeTagStruct, otherwise false.
*/
isStruct(): this is TypeTagStruct;
/**
* Determines if the current instance is of type `TypeTagU8`.
*
* @returns {boolean} Returns true if the instance is of type `TypeTagU8`, otherwise false.
*/
isU8(): this is TypeTagU8;
/**
* Checks if the current instance is of type TypeTagU16.
*
* @returns {boolean} True if the instance is TypeTagU16, otherwise false.
*/
isU16(): this is TypeTagU16;
/**
* Checks if the current instance is of type TypeTagU32.
*
* @returns {boolean} Returns true if the instance is TypeTagU32, otherwise false.
*/
isU32(): this is TypeTagU32;
/**
* Checks if the current instance is of type TypeTagU64.
*
* @returns {boolean} True if the instance is a TypeTagU64, otherwise false.
*/
isU64(): this is TypeTagU64;
/**
* Determines if the current instance is of the TypeTagU128 type.
*
* @returns {boolean} True if the instance is of TypeTagU128, otherwise false.
*/
isU128(): this is TypeTagU128;
/**
* Checks if the current instance is of type TypeTagU256.
*
* @returns {boolean} Returns true if the instance is of type TypeTagU256, otherwise false.
*/
isU256(): this is TypeTagU256;
isPrimitive(): boolean;
}
/**
* Represents a boolean type tag in the type system.
* This class extends the base TypeTag class and provides
* methods for serialization and deserialization of the boolean
* type tag.
*
* @extends TypeTag
*/
declare class TypeTagBool extends TypeTag {
/**
* Returns the string representation of the object.
*
* @returns {string} The string representation of the object.
*/
toString(): string;
/**
* Serializes the current instance's properties into a provided serializer.
* This function ensures that the address, module name, name, and type arguments are properly serialized.
*
* @param serializer - The serializer instance used to serialize the properties.
*/
serialize(serializer: Serializer): void;
/**
* Deserializes a StructTag and returns a new TypeTagStruct instance.
*
* @param _deserializer - The deserializer used to read the StructTag data.
*/
static load(_deserializer: Deserializer): TypeTagBool;
}
/**
* Represents a type tag for an 8-bit unsigned integer (u8).
* This class extends the base TypeTag class and provides methods
* for serialization and deserialization specific to the u8 type.
*
* @extends TypeTag
*/
declare class TypeTagU8 extends TypeTag {
toString(): string;
serialize(serializer: Serializer): void;
static load(_deserializer: Deserializer): TypeTagU8;
}
/**
* Represents a type tag for unsigned 16-bit integers (u16).
* This class extends the base TypeTag class and provides methods for serialization and deserialization.
*
* @extends TypeTag
*/
declare class TypeTagU16 extends TypeTag {
toString(): string;
serialize(serializer: Serializer): void;
static load(_deserializer: Deserializer): TypeTagU16;
}
/**
* Represents a type tag for a 32-bit unsigned integer (u32).
* This class extends the base TypeTag class and provides methods for serialization
* and deserialization specific to the u32 type.
*
* @extends TypeTag
*/
declare class TypeTagU32 extends TypeTag {
toString(): string;
serialize(serializer: Serializer): void;
static load(_deserializer: Deserializer): TypeTagU32;
}
/**
* Represents a type tag for 64-bit unsigned integers (u64).
* This class extends the base TypeTag class and provides methods for serialization and deserialization.
*
* @extends TypeTag
*/
declare class TypeTagU64 extends TypeTag {
toString(): string;
serialize(serializer: Serializer): void;
static load(_deserializer: Deserializer): TypeTagU64;
}
/**
* Represents a type tag for the u128 data type.
* This class extends the base TypeTag class and provides methods for serialization and deserialization.
*
* @extends TypeTag
*/
declare class TypeTagU128 extends TypeTag {
toString(): string;
serialize(serializer: Serializer): void;
static load(_deserializer: Deserializer): TypeTagU128;
}
/**
* Represents a type tag for the U256 data type.
* This class extends the base TypeTag class and provides methods for serialization and deserialization.
*
* @extends TypeTag
*/
declare class TypeTagU256 extends TypeTag {
toString(): string;
serialize(serializer: Serializer): void;
static load(_deserializer: Deserializer): TypeTagU256;
}
/**
* Represents a type tag for an address in the system.
* This class extends the TypeTag class and provides functionality
* to serialize the address type and load it from a deserializer.
*
* @extends TypeTag
*/
declare class TypeTagAddress extends TypeTag {
toString(): string;
serialize(serializer: Serializer): void;
static load(_deserializer: Deserializer): TypeTagAddress;
}
/**
* Represents a type tag for a signer in the system.
* This class extends the base TypeTag and provides specific functionality
* related to the signer type.
*
* @extends TypeTag
*/
declare class TypeTagSigner extends TypeTag {
toString(): string;
serialize(serializer: Serializer): void;
static load(_deserializer: Deserializer): TypeTagSigner;
}
/**
* Represents a reference to a type tag in the type system.
* This class extends the TypeTag class and provides functionality
* to serialize and deserialize type tag references.
*
* @extends TypeTag
*/
declare class TypeTagReference extends TypeTag {
readonly value: TypeTag;
toString(): `&${string}`;
/**
* Initializes a new instance of the class with the specified parameters.
*
* @param value - The TypeTag to reference.
*/
constructor(value: TypeTag);
serialize(serializer: Serializer): void;
static load(deserializer: Deserializer): TypeTagReference;
}
/**
* Represents a generic type tag used for type parameters in entry functions.
* Generics are not serialized into a real type, so they cannot be used as a type directly.
*
* @extends TypeTag
*/
declare class TypeTagGeneric extends TypeTag {
readonly value: number;
toString(): `T${number}`;
constructor(value: number);
serialize(serializer: Serializer): void;
static load(deserializer: Deserializer): TypeTagGeneric;
}
/**
* Represents a vector type tag, which encapsulates a single type tag value.
* This class extends the base TypeTag class and provides methods for serialization,
* deserialization, and string representation of the vector type tag.
*
* @extends TypeTag
*/
declare class TypeTagVector extends TypeTag {
readonly value: TypeTag;
toString(): `vector<${string}>`;
constructor(value: TypeTag);
/**
* Creates a new TypeTagVector instance with a TypeTagU8 type.
*
* @returns {TypeTagVector} A new TypeTagVector initialized with TypeTagU8.
*/
static u8(): TypeTagVector;
serialize(serializer: Serializer): void;
static load(deserializer: Deserializer): TypeTagVector;
}
/**
* Represents a structured type tag in the system, extending the base TypeTag class.
* This class encapsulates information about a specific structure, including its address,
* module name, and type arguments, and provides methods for serialization and type checking.
*
* @param value - The StructTag instance containing the details of the structured type.
*/
declare class TypeTagStruct extends TypeTag {
readonly value: StructTag;
toString(): `0x${string}::${string}::${string}`;
constructor(value: StructTag);
serialize(serializer: Serializer): void;
static load(deserializer: Deserializer): TypeTagStruct;
/**
* Determines if the provided address, module name, and struct name match the current type tag.
*
* @param address - The account address to compare against the type tag.
* @param moduleName - The name of the module to compare against the type tag.
* @param structName - The name of the struct to compare against the type tag.
* @returns True if the address, module name, and struct name match the type tag; otherwise, false.
*/
isTypeTag(address: AccountAddress, moduleName: string, structName: string): boolean;
/**
* Checks if the provided value is of type string.
* This function can help ensure that the data being processed is in the correct format before further operations.
*
* @returns {boolean} Returns true if the value is a string, otherwise false.
*/
isString(): boolean;
/**
* Checks if the specified account address is of type "option".
*
* @returns {boolean} Returns true if the account address is an option type, otherwise false.
*/
isOption(): boolean;
/**
* Checks if the provided value is of type 'object'.
* This function helps determine if a value can be treated as an object type in the context of the SDK.
*
* @returns {boolean} Returns true if the value is an object, otherwise false.
*/
isObject(): boolean;
}
/**
* Represents a structured tag that includes an address, module name,
* name, and type arguments. This class is used to define and manage
* structured data types within the SDK.
*
* @property {AccountAddress} address - The address associated with the struct tag.
* @property {Identifier} moduleName - The name of the module that contains the struct.
* @property {Identifier} name - The name of the struct.
* @property {Array<TypeTag>} typeArgs - An array of type arguments associated with the struct.
*/
declare class StructTag extends Serializable {
readonly address: AccountAddress;
readonly moduleName: Identifier;
readonly name: Identifier;
readonly typeArgs: Array<TypeTag>;
constructor(address: AccountAddress, module_name: Identifier, name: Identifier, type_args: Array<TypeTag>);
serialize(serializer: Serializer): void;
static deserialize(deserializer: Deserializer): StructTag;
}
/**
* Retrieves the StructTag for the AptosCoin, which represents the Aptos Coin in the Aptos blockchain.
*
* @returns {StructTag} The StructTag for the AptosCoin.
*/
declare function aptosCoinStructTag(): StructTag;
/**
* Returns a new StructTag representing a string type.
*
* @returns {StructTag} A StructTag for the string type.
*/
declare function stringStructTag(): StructTag;
/**
* Creates a new StructTag for the Option type with the specified type argument.
* This can help in defining a specific instance of an Option type in your application.
*
* @param typeArg - The type tag that specifies the type of the value contained in the Option.
*/
declare function optionStructTag(typeArg: TypeTag): StructTag;
/**
* Creates a new StructTag for the Object type with the specified type argument.
* This function helps in defining a structured representation of an Object with a specific type.
*
* @param typeArg - The type tag that specifies the type of the Object.
*/
declare function objectStructTag(typeArg: TypeTag): StructTag;
/**
* Deserialize a Script Transaction Argument.
* This function retrieves and deserializes various types of script transaction arguments based on the provided deserializer.
*
* @param deserializer - The deserializer used to read the script transaction argument.
* @returns The deserialized script transaction argument.
* @throws Error if the variant index is unknown.
*/
declare function deserializeFromScriptArgument(deserializer: Deserializer): TransactionArgument;
/**
* Represents a supported Transaction Payload that can be serialized and deserialized.
*
* This class serves as a base for different types of transaction payloads, allowing for
* their serialization into a format suitable for transmission and deserialization back
* into their original form.
*/
declare abstract class TransactionPayload extends Serializable {
/**
* Serialize a Transaction Payload
*/
abstract serialize(serializer: Serializer): void;
/**
* Deserialize a Transaction Payload
*/
/**
* Deserializes a multisig transaction payload from the provided deserializer.
* This function enables the reconstruction of a MultiSigTransactionPayload object from its serialized form.
*
* @param deserializer - The deserializer instance used to read the serialized data.
*/
static deserialize(deserializer: Deserializer): TransactionPayload;
}
/**
* Represents a transaction payload script that can be serialized and deserialized.
*
* This class encapsulates a script that defines the logic for a transaction payload.
*
* @extends TransactionPayload
*/
declare class TransactionPayloadScript extends TransactionPayload {
readonly script: Script;
/**
* Initializes a multi-sig account transaction with the provided payload.
*
* @param script - The payload of the multi-sig transaction. This can only be an EntryFunction for now, but Script might be
* supported in the future.
*/
constructor(script: Script);
/**
* Serializes the transaction payload, enabling future support for multiple types of inner transaction payloads.
*
* @param serializer - The serializer instance used to serialize the transaction data.
*/
serialize(serializer: Serializer): void;
/**
* Loads a MultiSig transaction payload from the provided deserializer.
* This function helps in reconstructing a MultiSig transaction payload from its serialized form.
*
* @param deserializer - The deserializer used to read the serialized data.
*/
static load(deserializer: Deserializer): TransactionPayloadScript;
}
/**
* Represents a transaction payload entry function that can be serialized and deserialized.
*
* @extends TransactionPayload
*/
declare class TransactionPayloadEntryFunction extends TransactionPayload {
readonly entryFunction: EntryFunction;
constructor(entryFunction: EntryFunction);
serialize(serializer: Serializer): void;
static load(deserializer: Deserializer): TransactionPayloadEntryFunction;
}
/**
* Represents a multi-signature transaction payload that can be serialized and deserialized.
*/
declare class TransactionPayloadMultiSig extends TransactionPayload {
readonly multiSig: MultiSig;
constructor(multiSig: MultiSig);
serialize(serializer: Serializer): void;
static load(deserializer: Deserializer): TransactionPayloadMultiSig;
}
/**
* Represents an entry function that can be serialized and deserialized.
* This class encapsulates the details required to invoke a function within a module,
* including the module name, function name, type arguments, and function arguments.
*
* @param module_name - Fully qualified module name in the format "account_address::module_name" (e.g., "0x1::coin").
* @param function_name - The name of the function (e.g., "transfer").
* @param type_args - Type arguments required by the Move function.
* @param args - Arguments to the Move function.
*/
declare class EntryFunction {
readonly module_name: ModuleId;
readonly function_name: Identifier;
readonly type_args: Array<TypeTag>;
readonly args: Array<EntryFunctionArgument>;
/**
* Contains the payload to run a function within a module.
* @param module_name Fully qualified module name in format "account_address::module_name" e.g. "0x1::coin"
* @param function_name The function name. e.g "transfer"
* @param type_args Type arguments that move function requires.
*
* @example
* A coin transfer function has one type argument "CoinType".
* ```
* public entry fun transfer<CoinType>(from: &signer, to: address, amount: u64)
* ```
* @param args arguments to the move function.
*
* @example
* A coin transfer function has three arguments "from", "to" and "amount".
* ```
* public entry fun transfer<CoinType>(from: &signer, to: address, amount: u64)
* ```
*/
constructor(module_name: ModuleId, function_name: Identifier, type_args: Array<TypeTag>, args: Array<EntryFunctionArgument>);
/**
* Build an EntryFunction payload from raw primitive values.
*
* @param module_id - Fully qualified module name in the format "AccountAddress::module_id", e.g., "0x1::coin".
* @param function_name - The name of the function to be called.
* @param type_args - Type arguments that the Move function requires.
* @param args - Arguments to the Move function.
*
* @example
* A coin transfer function has one type argument "CoinType".
* ```
* public(script) fun transfer<CoinType>(from: &signer, to: address, amount: u64)
* ```
*
* A coin transfer function has three arguments "from", "to", and "amount".
* ```
* public(script) fun transfer<CoinType>(from: &signer, to: address, amount: u64)
* ```
*
* @returns EntryFunction
*/
static build(module_id: MoveModuleId, function_name: string, type_args: Array<TypeTag>, args: Array<EntryFunctionArgument>): EntryFunction;
serialize(serializer: Serializer): void;
/**
* Deserializes an entry function payload with the arguments represented as EntryFunctionBytes instances.
* @see EntryFunctionBytes
*
* NOTE: When you deserialize an EntryFunction payload with this method, the entry function
* arguments are populated into the deserialized instance as type-agnostic, raw fixed bytes
* in the form of the EntryFunctionBytes class.
*
* In order to correctly deserialize these arguments as their actual type representations, you
* must know the types of the arguments beforehand and deserialize them yourself individually.
*
* One way you could achieve this is by using the ABIs for an entry function and deserializing each
* argument as its given, corresponding type.
*
* @param deserializer
* @returns A deserialized EntryFunction payload for a transaction.
*
*/
static deserialize(deserializer: Deserializer): EntryFunction;
}
/**
* Represents a Script that can be serialized and deserialized.
* Scripts contain the Move bytecode payload that can be submitted to the Aptos chain for execution.
*/
declare class Script {
/**
* The move module bytecode
*/
readonly bytecode: Uint8Array;
/**
* The type arguments that the bytecode function requires.
*/
readonly type_args: Array<TypeTag>;
/**
* The arguments that the bytecode function requires.
*/
readonly args: Array<ScriptFunctionArgument>;
/**
* Scripts contain the Move bytecodes payload that can be submitted to Aptos chain for execution.
*
* @param bytecode The move module bytecode
* @param type_args The type arguments that the bytecode function requires.
*
* @example
* A coin transfer function has one type argument "CoinType".
* ```
* public(script) fun transfer<CoinType>(from: &signer, to: address, amount: u64)
* ```
* @param args The arguments that the bytecode function requires.
*
* @example
* A coin transfer function has three arguments "from", "to" and "amount".
* ```
* public(script) fun transfer<CoinType>(from: &signer, to: address, amount: u64)
* ```
*/
constructor(bytecode: Uint8Array, type_args: Array<TypeTag>, args: Array<ScriptFunctionArgument>);
serialize(serializer: Serializer): void;
static deserialize(deserializer: Deserializer): Script;
}
/**
* Represents a MultiSig account that can be serialized and deserialized.
*
* This class encapsulates the functionality to manage multi-signature transactions, including the address of the
* multi-sig account and the associated transaction payload.
*/
declare class MultiSig {
readonly multisig_address: AccountAddress;
readonly transaction_payload?: MultiSigTransactionPayload;
/**
* Contains the payload to run a multi-sig account transaction.
*
* @param multisig_address The multi-sig account address the transaction will be executed as.
*
* @param transaction_payload The payload of the multi-sig transaction. This is optional when executing a multi-sig
* transaction whose payload is already stored on chain.
*/
constructor(multisig_address: AccountAddress, transaction_payload?: MultiSigTransactionPayload);
serialize(serializer: Serializer): void;
static deserialize(deserializer: Deserializer): MultiSig;
}
/**
* Represents a multi-signature transaction payload that can be serialized and deserialized.
* This class is designed to encapsulate the transaction payload for multi-sig account transactions
* as defined in the `multisig_account.move` module. Future enhancements may allow support for script
* payloads as the `multisig_account.move` module evolves.
*/
declare class MultiSigTransactionPayload extends Serializable {
readonly transaction_payload: EntryFunction;
/**
* Contains the payload to run a multi-sig account transaction.
*
* @param transaction_payload The payload of the multi-sig transaction.
* This can only be EntryFunction for now but,
* Script might be supported in the future.
*/
constructor(transaction_payload: EntryFunction);
serialize(serializer: Serializer): void;
static deserialize(deserializer: Deserializer): MultiSigTransactionPayload;
}
/**
* Represents a raw transaction that can be serialized and deserialized.
* Raw transactions contain the metadata and payloads that can be submitted to the Aptos chain for execution.
* They must be signed before the Aptos chain can execute them.
*/
declare class RawTransaction extends Serializable {
readonly sender: AccountAddress;
readonly sequence_number: bigint;
readonly payload: TransactionPayload;
readonly max_gas_amount: bigint;
readonly gas_unit_price: bigint;
readonly expiration_timestamp_secs: bigint;
readonly chain_id: ChainId;
/**
* RawTransactions contain the metadata and payloads that can be submitted to Aptos chain for execution.
* RawTransactions must be signed before Aptos chain can execute them.
*
* @param sender The sender Account Address
* @param sequence_number Sequence number of this transaction. This must match the sequence number stored in
* the sender's account at the time the transaction executes.
* @param payload Instructions for the Aptos Blockchain, including publishing a module,
* execute an entry function or execute a script payload.
* @param max_gas_amount Maximum total gas to spend for this transaction. The account must have more
* than this gas or the transaction will be discarded during validation.
* @param gas_unit_price Price to be paid per gas unit.
* @param expiration_timestamp_secs The blockchain timestamp at which the blockchain would discard this transaction.
* @param chain_id The chain ID of the blockchain that this transaction is intended to be run on.
*/
constructor(sender: AccountAddress, sequence_number: bigint, payload: TransactionPayload, max_gas_amount: bigint, gas_unit_price: bigint, expiration_timestamp_secs: bigint, chain_id: ChainId);
/**
* Serializes the transaction data, including the fee payer transaction type, raw transaction, secondary signer addresses,
* and fee payer address.
* This function is essential for preparing the transaction for transmission or storage in a serialized format.
*
* @param serializer - The serializer instance used to serialize the transaction data.
*/
serialize(serializer: Serializer): void;
/**
* Deserialize a Raw Transaction With Data.
* This function retrieves the appropriate raw transaction based on the variant index provided by the deserializer.
*
* @param deserializer - An instance of the Deserializer used to read the serialized data.
*/
static deserialize(deserializer: Deserializer): RawTransaction;
}
/**
* Represents a raw transaction with associated data that can be serialized and deserialized.
*
* @extends Serializable
*/
declare abstract class RawTransactionWithData extends Serializable {
/**
* Serialize a Raw Transaction With Data
*/
abstract serialize(serializer: Serializer): void;
/**
* Deserialize a Raw Transaction With Data
*/
static deserialize(deserializer: Deserializer): RawTransactionWithData;
}
/**
* Represents a multi-agent transaction that can be serialized and deserialized.
*
* @extends RawTransactionWithData
*/
declare class MultiAgentRawTransaction extends RawTransactionWithData {
/**
* The raw transaction
*/
readonly raw_txn: RawTransaction;
/**
* The secondary signers on this transaction
*/
readonly secondary_signer_addresses: Array<AccountAddress>;
constructor(raw_txn: RawTransaction, secondary_signer_addresses: Array<AccountAddress>);
serialize(serializer: Serializer): void;
/**
* Deserializes a Fee Payer Raw Transaction from the provided deserializer.
* This function allows you to reconstruct a Fee Payer Raw Transaction object, which includes the raw transaction data,
* secondary signer addresses, and the fee payer address.
*
* @param deserializer - The deserializer used to read the raw transaction data.
* @returns A FeePayerRawTransaction object constructed from the deserialized data.
*/
static load(deserializer: Deserializer): MultiAgentRawTransaction;
}
/**
* Represents a Fee Payer Transaction that can be serialized and deserialized.
*/
declare class FeePayerRawTransaction extends RawTransactionWithData {
/**
* The raw transaction
*/
readonly raw_txn: RawTransaction;
/**
* The secondary signers on this transaction - optional and can be empty
*/
readonly secondary_signer_addresses: Array<AccountAddress>;
/**
* The fee payer account address
*/
readonly fee_payer_address: AccountAddress;
constructor(raw_txn: RawTransaction, secondary_signer_addresses: Array<AccountAddress>, fee_payer_address: AccountAddress);
serialize(serializer: Serializer): void;
static load(deserializer: Deserializer): FeePayerRawTransaction;
}
/**
* Represents a challenge required for the account owner to sign in order to rotate the authentication key.
*/
declare class RotationProofChallenge extends Serializable {
readonly accountAddress: AccountAddress;
readonly moduleName: MoveString;
readonly structName: MoveString;
readonly originator: AccountAddress;
readonly currentAuthKey: AccountAddress;
readonly newPublicKey: MoveVector<U8>;
readonly sequenceNumber: U64;
/**
* Initializes a new instance of the class with the specified parameters.
* This constructor sets up the necessary attributes for managing account keys.
*
* @param args - The parameters required to create the instance.
* @param args.sequenceNumber - The sequence number associated with the transaction.
* @param args.originator - The account address of the originator.
* @param args.currentAuthKey - The current authentication key of the account.
* @param args.newPublicKey - The new public key to be set for the account.
*/
constructor(args: {
sequenceNumber: AnyNumber;
originator: AccountAddress;
currentAuthKey: AccountAddress;
newPublicKey: PublicKey;
});
/**
* Serializes the properties of the current instance for transmission or storage.
* This function helps in converting the instance data into a format suitable for serialization.
*
* @param serializer - The serializer used to serialize the instance properties.
* @param serializer.accountAddress - The account address to serialize.
* @param serializer.moduleName - The module name to serialize.
* @param serializer.structName - The struct name to serialize.
* @param serializer.sequenceNumber - The sequence number to serialize.
* @param serializer.originator - The originator to serialize.
* @param serializer.currentAuthKey - The current authentication key to serialize.
* @param serializer.newPublicKey - The new public key to serialize.
*/
serialize(serializer: Serializer): void;
}
/**
* Represents an abstract base class for transaction authenticators.
* This class provides methods for serializing and deserializing different types of transaction authenticators.
*
* @extends Serializable
*/
declare abstract class TransactionAuthenticator extends Serializable {
abstract serialize(serializer: Serializer): void;
/**
* Deserializes a TransactionAuthenticator from the provided deserializer.
* This function helps in reconstructing the TransactionAuthenticator based on the variant index found in the serialized data.
*
* @param deserializer - The deserializer instance used to read the serialized data.
*/
static deserialize(deserializer: Deserializer): TransactionAuthenticator;
isEd25519(): this is TransactionAuthenticatorEd25519;
isMultiEd25519(): this is TransactionAuthenticatorMultiEd25519;
isMultiAgent(): this is TransactionAuthenticatorMultiAgent;
isFeePayer(): this is TransactionAuthenticatorFeePayer;
isSingleSender(): this is TransactionAuthenticatorSingleSender;
}
/**
* Represents a transaction authenticator using Ed25519 for a single signer transaction.
* This class encapsulates the client's public key and the Ed25519 signature of a raw transaction.
*
* @param public_key - The client's public key.
* @param signature - The Ed25519 signature of a raw transaction.
* @see {@link https://aptos.dev/integration/creating-a-signed-transaction | Creating a Signed Transaction}
* for details about generating a signature.
*/
declare class TransactionAuthenticatorEd25519 extends TransactionAuthenticator {
readonly public_key: Ed25519PublicKey;
readonly signature: Ed25519Signature;
/**
* Creates an instance of the class with the specified account authenticator.
*
* @param public_key - The Ed25519PublicKey that will be used for authentication.
* @param signature - The Ed25519Signature that will be used for authentication.
*/
constructor(public_key: Ed25519PublicKey, signature: Ed25519Signature);
/**
* Serializes the transaction authenticator by encoding the sender information.
*
* @param serializer - The serializer instance used to perform the serialization.
*/
serialize(serializer: Serializer): void;
/**
* Loads a TransactionAuthenticatorSingleSender instance from the provided deserializer.
* This function helps in deserializing the sender information to create a transaction authenticator.
*
* @param deserializer - The deserializer used to extract the sender data.
*/
static load(deserializer: Deserializer): TransactionAuthenticatorEd25519;
}
/**
* Represents a transaction authenticator for multi-signature transactions using Ed25519.
* This class is used to validate transactions that require multiple signatures from different signers.
*
* @param public_key - The public key of the client involved in the transaction.
* @param signature - The multi-signature of the raw transaction.
*/
declare class TransactionAuthenticatorMultiEd25519 extends TransactionAuthenticator {
readonly public_key: MultiEd25519PublicKey;
readonly signature: MultiEd25519Signature;
constructor(public_key: MultiEd25519PublicKey, signature: MultiEd25519Signature);
serialize(serializer: Serializer): void;
static load(deserializer: Deserializer): TransactionAuthenticatorMultiEd25519;
}
/**
* Represents a transaction authenticator for a multi-agent transaction.
*
* This class manages the authentication process involving a primary sender and multiple secondary signers.
*
* @param sender - The authenticator for the sender account.
* @param secondary_signer_addresses - An array of addresses for the secondary signers.
* @param secondary_signers - An array of authenticators for the secondary signer accounts.
*/
declare class TransactionAuthenticatorMultiAgent extends TransactionAuthenticator {
readonly sender: AccountAuthenticator;
readonly secondary_signer_addresses: Array<AccountAddress>;
readonly secondary_signers: Array<AccountAuthenticator>;
constructor(sender: AccountAuthenticator, secondary_signer_addresses: Array<AccountAddress>, secondary_signers: Array<AccountAuthenticator>);
serialize(serializer: Serializer): void;
static load(deserializer: Deserializer): TransactionAuthenticatorMultiAgent;
}
/**
* Represents a transaction authenticator specifically for fee payer transactions.
* It encapsulates the sender's account authenticator, addresses of secondary signers,
* their respective authenticators, and the fee payer's account information.
*
* @param sender - The authenticator for the sender's account.
* @param secondary_signer_addresses - An array of addresses for secondary signers.
* @param secondary_signers - An array of authenticators for secondary signers' accounts.
* @param fee_payer - An object containing the fee payer's account address and authenticator.
*/
declare class TransactionAuthenticatorFeePayer extends TransactionAuthenticator {
readonly sender: AccountAuthenticator;
readonly secondary_signer_addresses: Array<AccountAddress>;
readonly secondary_signers: Array<AccountAuthenticator>;
readonly fee_payer: {
address: AccountAddress;
authenticator: AccountAuthenticator;
};
constructor(sender: AccountAuthenticator, secondary_signer_addresses: Array<AccountAddress>, secondary_signers: Array<AccountAuthenticator>, fee_payer: {
address: AccountAddress;
authenticator: AccountAuthenticator;
});
serialize(serializer: Serializer): void;
static load(deserializer: Deserializer): TransactionAuthenticatorMultiAgent;
}
/**
* Represents a single sender authenticator for transactions that require a single signer.
* This class is responsible for managing the authentication of a transaction initiated by a single sender.
*
* @param sender - An instance of AccountAuthenticator that represents the account of the sender.
*/
declare class TransactionAuthenticatorSingleSender extends TransactionAuthenticator {
readonly sender: AccountAuthenticator;
constructor(sender: AccountAuthenticator);
serialize(serializer: Serializer): void;
static load(deserializer: Deserializer): TransactionAuthenticatorSingleSender;
}
/**
* Represents a signed transaction that includes a raw transaction and an authenticator.
* The authenticator contains a client's public key and the signature of the raw transaction.
*
* @see {@link https://aptos.dev/integration/creating-a-signed-transaction | Creating a Signed Transaction}
* @param raw_txn - The raw transaction to be signed.
* @param authenticator - Contains a client's public key and the signature of the raw transaction.
* Authenticator can have three variations: single signature, multi-signature, and multi-agent.
* @see {@link https://github.com/aptos-labs/aptos-core/blob/main/types/src/transaction/authenticator.rs} for details.
*/
declare class SignedTransaction extends Serializable {
readonly raw_txn: RawTransaction;
readonly authenticator: TransactionAuthenticator;
/**
* Represents a signed transaction that includes a raw transaction and an authenticator.
* The authenticator contains a client's public key and the signature of the raw transaction,
* which can be of three types: single signature, multi-signature, and multi-agent.
*
* @param raw_txn The raw transaction to be signed.
* @param authenticator Contains a client's public key and the signature of the raw transaction. The authenticator has 3
* flavors: single signature, multi-signature and multi-agent.
* @see {@link https://aptos.dev/integration/creating-a-signed-transaction | Creating a Signed Transaction}
* @see {@link https://github.com/aptos-labs/aptos-core/blob/main/types/src/transaction/authenticator.rs} for details.
*/
constructor(raw_txn: RawTransaction, authenticator: TransactionAuthenticator);
/**
* Serializes the raw transaction and its authenticator using the provided serializer.
* This function is essential for preparing the transaction data for transmission or storage.
*
* @param serializer - The serializer instance used to serialize the transaction and authenticator.
*/
serialize(serializer: Serializer): void;
/**
* Deserializes a signed transaction from the provided deserializer.
* This function allows you to reconstruct a SignedTransaction object from its serialized form, enabling further processing or validation.
*
* @param deserializer - The deserializer instance used to read the serialized data.
*/
static deserialize(deserializer: Deserializer): SignedTransaction;
}
/**
* Represents a simple transaction type that can be submitted to the Aptos chain for execution.
*
* This transaction type is designed for a single signer and includes metadata such as the Raw Transaction
* and an optional sponsor Account Address to cover gas fees.
*
* @param rawTransaction - The Raw Transaction.
* @param feePayerAddress - The optional sponsor Account Address.
*/
declare class SimpleTransaction extends Serializable {
rawTransaction: RawTransaction;
feePayerAddress?: AccountAddress | undefined;
readonly secondarySignerAddresses: undefined;
/**
* SimpleTransaction represents a transaction signed by a single account that
* can be submitted to the Aptos chain for execution.
*
* @param rawTransaction The Raw Transaction.
* @param feePayerAddress The optional sponsor Account Address to pay the gas fees.
*/
constructor(rawTransaction: RawTransaction, feePayerAddress?: AccountAddress);
/**
* Serializes the transaction data using the provided serializer.
* This function ensures that the raw transaction and fee payer address are properly serialized for further processing.
*
* @param serializer - The serializer instance used to serialize the transaction data.
*/
serialize(serializer: Serializer): void;
/**
* Deserializes a SimpleTransaction from the given deserializer.
* This function helps in reconstructing a SimpleTransaction object from its serialized form.
*
* @param deserializer - The deserializer instance used to read the serialized data.
*/
static deserialize(deserializer: Deserializer): SimpleTransaction;
}
/**
* Represents a multi-agent transaction that can be serialized and deserialized.
* This transaction includes a raw transaction, optional fee payer address, and multiple secondary signer addresses.
*
* @param rawTransaction The raw transaction to be executed.
* @param secondarySignerAddresses An array of secondary signer addresses involved in the transaction.
* @param feePayerAddress An optional account address that sponsors the transaction's gas fees.
*/
declare class MultiAgentTransaction extends Serializable {
rawTransaction: RawTransaction;
feePayerAddress?: AccountAddress | undefined;
secondarySignerAddresses: AccountAddress[];
/**
* Represents a MultiAgentTransaction that can be submitted to the Aptos chain for execution.
* This class encapsulates the raw transaction data, the secondary signer addresses, and an optional fee payer address.
*
* @param rawTransaction The raw transaction data.
* @param secondarySignerAddresses An array of secondary signer addresses.
* @param feePayerAddress An optional account address that sponsors the gas fees.
*/
constructor(rawTransaction: RawTransaction, secondarySignerAddresses: AccountAddress[], feePayerAddress?: AccountAddress);
/**
* Serializes the transaction data, including the raw transaction, secondary signer addresses, and fee payer address.
* This function is essential for preparing the transaction for transmission or storage in a serialized format.
*
* @param serializer - The serializer instance used to serialize the transaction data.
*/
serialize(serializer: Serializer): void;
/**
* Deserializes a MultiAgentTransaction from the provided deserializer.
* This function allows you to reconstruct a MultiAgentTransaction object from its serialized form, including any secondary
* signer addresses and the fee payer address if present.
*
* @param deserializer - The deserializer instance used to read the serialized data.
*/
static deserialize(deserializer: Deserializer): MultiAgentTransaction;
}
/**
* Entry function arguments for building a raw transaction using remote ABI, supporting various data types including primitives and arrays.
*/
type SimpleEntryFunctionArgumentTypes = boolean | number | bigint | string | null | undefined | Uint8Array | ArrayBuffer | Array<SimpleEntryFunctionArgumentTypes | EntryFunctionArgumentTypes>;
/**
* Entry function arguments for building a raw transaction using BCS serialized arguments.
*/
type EntryFunctionArgumentTypes = Bool | U8 | U16 | U32 | U64 | U128 | U256 | AccountAddress | MoveVector<EntryFunctionArgumentTypes> | MoveOption<EntryFunctionArgumentTypes> | MoveString | FixedBytes;
/**
* Script function arguments for building raw transactions using BCS serialized arguments.
*/
type ScriptFunctionArgumentTypes = Bool | U8 | U16 | U32 | U64 | U128 | U256 | AccountAddress | MoveVector<ScriptFunctionArgumentTypes> | MoveString | FixedBytes | Serialized;
/**
* Inputs for Entry functions, view functions, and scripts, which can be a string representation of various types including
* primitive types, vectors, and structured types.
*
* *
* This can be a string version of the type argument such as:
* - u8
* - u16
* - u32
* - u64
* - u128
* - u256
* - bool
* - address
* - signer
* - vector<Type>
* - address::module::struct
* - address::module::struct<Type1, Type2>
*/
type TypeArgument = TypeTag | string;
/**
* Holds all return interfaces for generating different transaction types.
*/
type AnyRawTransactionInstance = RawTransaction | MultiAgentRawTransaction | FeePayerRawTransaction;
/**
* Optional options to set when generating a transaction, including a maximum gas amount.
*/
type InputGenerateTransactionOptions = {
maxGasAmount?: number;
gasUnitPrice?: number;
expireTimestamp?: number;
accountSequenceNumber?: AnyNumber;
};
/**
* The transaction payload type generated from the `generateTransactionPayload()` function, which can be an entry function,
* script, or multi-signature payload.
*/
type AnyTransactionPayloadInstance = TransactionPayloadEntryFunction | TransactionPayloadScript | TransactionPayloadMultiSig;
/**
* The data needed to generate a transaction payload for Entry Function, Script, or Multi Sig types.
*/
type InputGenerateTransactionPayloadData = InputEntryFunctionData | InputScriptData | InputMultiSigData;
/**
* The payload for generating a transaction, which can be either script data, entry function data with remote ABI, or
* multi-signature data.
*/
type InputGenerateTransactionPayloadDataWithRemoteABI = InputScriptData | InputEntryFunctionDataWithRemoteABI | InputMultiSigDataWithRemoteABI;
/**
* The data needed to generate an Entry Function payload.
*/
type InputEntryFunctionData = {
function: MoveFunctionId;
typeArguments?: Array<TypeArgument>;
functionArguments: Array<EntryFunctionArgumentTypes | SimpleEntryFunctionArgumentTypes>;
abi?: EntryFunctionABI;
};
/**
* The payload for generating a transaction, which can be either an entry function or a multi-signature transaction.
*/
type InputGenerateTransactionPayloadDataWithABI = InputEntryFunctionDataWithABI | InputMultiSigDataWithABI;
/**
* The input data for an entry function, including its associated ABI.
*/
type InputEntryFunctionDataWithABI = Omit<InputEntryFunctionData, "abi"> & {
abi: EntryFunctionABI;
};
/**
* The data needed to generate a Multi Sig payload, including the multisig address.
*/
type InputMultiSigDataWithABI = {
multisigAddress: AccountAddressInput;
} & InputEntryFunctionDataWithABI;
/**
* Combines input function data with Aptos configuration for remote ABI interactions.
*/
type InputEntryFunctionDataWithRemoteABI = InputEntryFunctionData & {
aptosConfig: AptosConfig;
};
/**
* The data needed to generate a Multi Sig payload
*/
type InputMultiSigData = {
multisigAddress: AccountAddressInput;
} & InputEntryFunctionData;
/**
* The data needed to generate a Multi Sig payload, including the multisig address.
*/
type InputMultiSigDataWithRemoteABI = {
multisigAddress: AccountAddressInput;
} & InputEntryFunctionDataWithRemoteABI;
/**
* The data needed to generate a Script payload.
*/
type InputScriptData = {
bytecode: HexInput;
typeArguments?: Array<TypeArgument>;
functionArguments: Array<ScriptFunctionArgumentTypes>;
};
/**
* The data needed to generate a View Function payload.
*/
type InputViewFunctionData = {
function: MoveFunctionId;
typeArguments?: Array<TypeArgument>;
functionArguments?: Array<EntryFunctionArgumentTypes | SimpleEntryFunctionArgumentTypes>;
abi?: ViewFunctionABI;
};
/**
* The data needed to generate a View Function payload in JSON format.
*/
type InputViewFunctionJsonData = {
function: MoveFunctionId;
typeArguments?: Array<MoveStructId>;
functionArguments?: Array<MoveValue>;
};
/**
* The payload sent to the fullnode for a JSON view request.
*/
type ViewFunctionJsonPayload = {
function: MoveFunctionId;
typeArguments: Array<MoveStructId>;
functionArguments: Array<MoveValue>;
};
/**
* Data required to create a view function payload and retrieve the remote ABI, including Aptos configuration.
*/
type InputViewFunctionDataWithRemoteABI = InputViewFunctionData & {
aptosConfig: AptosConfig;
};
/**
* Data needed to generate a view function, including the fetched ABI.
*/
type InputViewFunctionDataWithABI = InputViewFunctionData & {
abi: ViewFunctionABI;
};
/**
* Data needed for a generic function ABI, applicable to both view and entry functions.
*/
type FunctionABI = {
typeParameters: Array<MoveFunctionGenericTypeParam>;
parameters: Array<TypeTag>;
};
/**
* Interface for an Entry function's ABI, enabling type checking and input conversion for ABI-based transaction submissions.
*/
type EntryFunctionABI = FunctionABI & {
signers?: number;
};
/**
* Interface for a view function's ABI, providing type checking and input conversion for ABI-based transaction submissions.
*/
type ViewFunctionABI = FunctionABI & {
returnTypes: Array<TypeTag>;
};
/**
* Arguments for generating a single signer raw transaction, used in the transaction builder flow.
*
* @param aptosConfig - Configuration settings for Aptos.
* @param sender - The address of the sender.
* @param payload - The transaction payload.
* @param options - Optional transaction generation options.
* @param feePayerAddress - Optional address of the fee payer.
*/
interface InputGenerateSingleSignerRawTransactionArgs {
aptosConfig: AptosConfig;
sender: AccountAddressInput;
payload: AnyTransactionPayloadInstance;
options?: InputGenerateTransactionOptions;
feePayerAddress?: AccountAddressInput;
}
/**
* Arguments for generating a multi-agent transaction, used in the `generateTransaction()` method of the transaction builder flow.
*
* @param aptosConfig - Configuration settings for Aptos.
* @param sender - The address of the transaction sender.
* @param payload - The transaction payload.
* @param secondarySignerAddresses - List of secondary signer addresses.
* @param options - Optional settings for transaction generation.
* @param feePayerAddress - Optional address of the fee payer.
*/
interface InputGenerateMultiAgentRawTransactionArgs {
aptosConfig: AptosConfig;
sender: AccountAddressInput;
payload: AnyTransactionPayloadInstance;
secondarySignerAddresses: AccountAddressInput[];
options?: InputGenerateTransactionOptions;
feePayerAddress?: AccountAddressInput;
}
/**
* A unified type for generating various transaction types.
*/
type InputGenerateRawTransactionArgs = InputGenerateSingleSignerRawTransactionArgs | InputGenerateMultiAgentRawTransactionArgs;
/**
* Unified type that holds all the return interfaces when generating different transaction types
*/
type AnyRawTransaction = SimpleTransaction | MultiAgentTransaction;
/**
* The data required to simulate a transaction, typically generated by `generateTransaction()`.
*/
type InputSimulateTransactionData = {
/**
* The transaction to simulate, probably generated by `generateTransaction()`
*/
transaction: AnyRawTransaction;
/**
* For a single signer transaction
* This is optional and can be undefined to skip the public/auth key check during the transaction simulation.
*/
signerPublicKey?: PublicKey;
/**
* For a fee payer or multi-agent transaction that requires additional signers in
*/
secondarySignersPublicKeys?: Array<PublicKey | undefined>;
/**
* For a fee payer transaction (aka Sponsored Transaction)
*/
feePayerPublicKey?: PublicKey;
options?: InputSimulateTransactionOptions;
};
/**
* Options for simulating a transaction input, including whether to estimate the gas unit price.
*/
type InputSimulateTransactionOptions = {
estimateGasUnitPrice?: boolean;
estimateMaxGasAmount?: boolean;
estimatePrioritizedGasUnitPrice?: boolean;
};
/**
* Holds user input data for generating a single signer transaction.
*
* @param sender - The address of the account sending the transaction.
* @param data - The payload data for the transaction.
* @param options - Optional transaction options.
* @param withFeePayer - Indicates if the fee payer is included.
* @param secondarySignerAddresses - Addresses for any secondary signers (not used in single signer transactions).
*/
interface InputGenerateSingleSignerRawTransactionData {
sender: AccountAddressInput;
data: InputGenerateTransactionPayloadData;
options?: InputGenerateTransactionOptions;
withFeePayer?: boolean;
secondarySignerAddresses?: undefined;
}
/**
* Holds user data input for generating a multi-agent transaction.
*
* @param sender - The address of the primary sender.
* @param data - The payload data for the transaction.
* @param secondarySignerAddresses - An array of addresses for secondary signers.
* @param options - Optional transaction options.
* @param withFeePayer - Indicates if a fee payer is included.
*/
interface InputGenerateMultiAgentRawTransactionData {
sender: AccountAddressInput;
data: InputGenerateTransactionPayloadData;
secondarySignerAddresses: AccountAddressInput[];
options?: InputGenerateTransactionOptions;
withFeePayer?: boolean;
}
/**
* Unified type holding user data input interfaces for generating various transaction types.
*/
type InputGenerateTransactionData = InputGenerateSingleSignerRawTransactionData | InputGenerateMultiAgentRawTransactionData;
/**
* Holds user data input for submitting a transaction.
*
* @param transaction - The raw transaction data.
* @param senderAuthenticator - The authenticator for the sender's account.
* @param feePayerAuthenticator - Optional authenticator for the fee payer's account.
* @param additionalSignersAuthenticators - Optional array of authenticators for additional signers.
*/
interface InputSubmitTransactionData {
transaction: AnyRawTransaction;
senderAuthenticator: AccountAuthenticator;
feePayerAuthenticator?: AccountAuthenticator;
additionalSignersAuthenticators?: Array<AccountAuthenticator>;
}
/**
* Arguments required to create a single key signer.
*
* @param privateKey - The private key used for signing.
* @param address - Optional account address associated with the signer.
*/
interface SingleKeySignerConstructorArgs {
privateKey: PrivateKey;
address?: AccountAddressInput;
}
/**
* Arguments for generating a single key signer.
*
* @param scheme - The signing scheme to be used.
*/
interface SingleKeySignerGenerateArgs {
scheme?: SigningSchemeInput;
}
/**
* The arguments for generating a single key signer from a specified derivation path.
*/
type SingleKeySignerFromDerivationPathArgs = SingleKeySignerGenerateArgs & {
path: string;
mnemonic: string;
};
/**
* Arguments required to verify a single key signature for a given message.
*
* @param message - The message to be verified, represented in hexadecimal format.
* @param signature - The signature that corresponds to the message.
*/
interface VerifySingleKeySignatureArgs {
message: HexInput;
signature: AnySignature;
}
/**
* Signer implementation for the SingleKey authentication scheme.
* This class extends a SingleKeyAccount by adding signing capabilities through a valid private key.
* Currently, the only supported signature schemes are Ed25519 and Secp256k1.
*
* Note: Generating a signer instance does not create the account on-chain.
*/
declare class SingleKeyAccount implements Account$1 {
/**
* Private key associated with the account
*/
readonly privateKey: PrivateKey;
readonly publicKey: AnyPublicKey;
readonly accountAddress: AccountAddress;
readonly signingScheme = SigningScheme.SingleKey;
/**
* Creates an instance of the SingleKeySigner using the provided private key and address.
* This allows for signing transactions and messages with the specified private key.
*
* @param args - The constructor arguments for initializing the SingleKeySigner.
* @param args.privateKey - The private key used for signing.
* @param args.address - The optional account address; if not provided, it will derive the address from the public key.
*/
constructor(args: SingleKeySignerConstructorArgs);
/**
* Derives an account from a randomly generated private key based on the specified signing scheme.
* The default generation scheme is Ed25519, but it can also support Secp256k1Ecdsa.
*
* @param args - The arguments for generating the account.
* @param args.scheme - The signing scheme to use for generating the private key. Defaults to SigningSchemeInput.Ed25519.
* @returns An account with the generated private key based on the specified signing scheme.
* @throws Error if an unsupported signature scheme is provided.
*/
static generate(args?: SingleKeySignerGenerateArgs): SingleKeyAccount;
/**
* Derives an account using a specified BIP44 path and mnemonic seed phrase, defaulting to the Ed25519 signature scheme.
* This function allows you to create a single key account based on the provided derivation path and mnemonic.
*
* @param args - The arguments for deriving the account.
* @param args.scheme - The signature scheme to derive the private key with. Defaults to Ed25519.
* @param args.path - The BIP44 derive hardened path (e.g. m/44'/637'/0'/0'/0') for Ed25519, or non-hardened path
* (e.g. m/44'/637'/0'/0/0) for secp256k1.
* Detailed description: {@link https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki}
* @param args.mnemonic - The mnemonic seed phrase of the account.
*/
static fromDerivationPath(args: SingleKeySignerFromDerivationPathArgs): SingleKeyAccount;
/**
* Verify the given message and signature with the public key.
*
* @param args - The arguments for verifying the signature.
* @param args.message - The raw message data in HexInput format.
* @param args.signature - The signed message signature.
* @returns A boolean indicating whether the signature is valid.
*/
verifySignature(args: VerifySingleKeySignatureArgs): boolean;
/**
* Sign a message using the account's private key and return an AccountAuthenticator containing the signature along with the
* account's public key.
* @param message - The signing message, represented as binary input in hexadecimal format.
* @returns An instance of AccountAuthenticatorSingleKey containing the signature and the public key.
*/
signWithAuthenticator(message: HexInput): AccountAuthenticatorSingleKey;
/**
* Sign a transaction using the account's private key.
* This function returns an AccountAuthenticator that contains the signature of the transaction along with the account's public key.
* @param transaction - The raw transaction to be signed.
* @returns An AccountAuthenticatorSingleKey containing the signature of the transaction and the account's public key.
*/
signTransactionWithAuthenticator(transaction: AnyRawTransaction): AccountAuthenticatorSingleKey;
/**
* Sign the given message using the account's private key.
* @param message - The message to be signed in HexInput format.
* @returns A new AnySignature containing the signature of the message.
*/
sign(message: HexInput): AnySignature;
/**
* Sign the given transaction using the account's private key.
* This function generates a signing message for the transaction and then signs it.
*
* @param transaction - The transaction to be signed.
* @returns Signature - The resulting signature for the signed transaction.
*/
signTransaction(transaction: AnyRawTransaction): AnySignature;
}
/**
* Arguments for creating an `Ed25519Account` from an `Ed25519PrivateKey`.
* To use the SingleKey authentication scheme, set `legacy` to false.
*
* @param privateKey - The private key used to create the account.
* @param address - Optional address for the account.
* @param legacy - Indicates whether to use legacy authentication (default is true).
*/
interface CreateEd25519AccountFromPrivateKeyArgs {
privateKey: Ed25519PrivateKey;
address?: AccountAddressInput;
legacy?: true;
}
/**
* Arguments for creating a `SingleKeyAccount` using an `Ed25519PrivateKey`.
* The `legacy` property must be set to false to utilize the `SingleKey` authentication scheme.
*
* @param privateKey - The Ed25519 private key used for account creation.
* @param address - Optional account address input.
* @param legacy - Must be false to enable the `SingleKey` authentication scheme.
*/
interface CreateEd25519SingleKeyAccountFromPrivateKeyArgs {
privateKey: Ed25519PrivateKey;
address?: AccountAddressInput;
legacy: false;
}
/**
* Arguments for creating a `SingleKeyAccount` from a supported private key, excluding `Ed25519PrivateKey`.
* The `legacy` argument is always false and cannot be set to true.
*
* @param privateKey - The private key used to create the account.
* @param address - Optional address input for the account.
* @param legacy - Always false; cannot be explicitly set to true.
*/
interface CreateSingleKeyAccountFromPrivateKeyArgs {
privateKey: Exclude<PrivateKey, Ed25519PrivateKey>;
address?: AccountAddressInput;
legacy?: false;
}
/**
* Arguments for creating an `Account` from a private key when the key type is unknown at compile time.
*
* @param privateKey - The private key used to create the account.
* @param address - Optional address for the account.
* @param legacy - Optional flag indicating if the account is a legacy account.
*/
interface CreateAccountFromPrivateKeyArgs {
privateKey: PrivateKey;
address?: AccountAddressInput;
legacy?: boolean;
}
/**
* Arguments for generating an Ed25519 account, specifying the signing scheme and legacy option.
*
* @param scheme - The signing scheme to use for the account.
* @param legacy - Indicates if the account should be created in legacy mode.
*/
interface GenerateEd25519AccountArgs {
scheme?: SigningSchemeInput.Ed25519;
legacy?: true;
}
/**
* Arguments for generating a `SingleKeyAccount` with an underlying `Ed25519PrivateKey`.
* The `legacy` argument must be set to false to ensure an `Ed25519SingleKeyAccount` is returned.
*
* @param scheme - Optional signing scheme input for the account.
* @param legacy - Indicates whether to use legacy account generation.
*/
interface GenerateEd25519SingleKeyAccountArgs {
scheme?: SigningSchemeInput.Ed25519;
legacy: false;
}
/**
* Arguments for generating a `SingleKeyAccount` using a supported private key other than `Ed25519PrivateKey`.
* The `legacy` argument is optional and defaults to false, and cannot be set to true.
*
* @param scheme - The signing scheme to use for the account.
* @param legacy - Indicates whether to use legacy account generation (defaults to false).
*/
interface GenerateSingleKeyAccountArgs {
scheme: Exclude<SigningSchemeInput, SigningSchemeInput.Ed25519>;
legacy?: false;
}
/**
* Arguments for generating an opaque `Account` when the input signature scheme is unknown at compile time.
*
* @param scheme - The signing scheme to use for account generation.
* @param legacy - Indicates whether to use legacy account generation methods.
*/
interface GenerateAccountArgs {
scheme?: SigningSchemeInput;
legacy?: boolean;
}
/**
* Arguments for deriving a private key using a mnemonic phrase and a specified BIP44 path.
*
* @param path - The BIP44 derivation path for the key.
* @param mnemonic - The mnemonic phrase used for key generation.
*/
interface PrivateKeyFromDerivationPathArgs {
path: string;
mnemonic: string;
}
/**
* Abstract class representing a generic Aptos account.
*
* This class serves as a single entry point for account generation, allowing accounts to be created
* either through `Account.generate()` or `Account.fromDerivationPath`. Although it is defined as an
* abstract class, it should be treated as an interface and enforced using the `implements` keyword.
*
* Note: Generating an account instance does not create the account on-chain.
*/
declare abstract class Account$1 {
/**
* Public key associated with the account
*/
abstract readonly publicKey: AccountPublicKey;
/**
* Account address associated with the account
*/
abstract readonly accountAddress: AccountAddress;
/**
* Signing scheme used to sign transactions
*/
abstract signingScheme: SigningScheme;
/**
* Generates a new account based on the specified signing scheme and legacy option.
* This function allows you to create an account with either the Ed25519 signing scheme or a different scheme as specified.
*
* @param args - The arguments for generating the account.
* @param args.scheme - The signing scheme to use for account generation. Defaults to Ed25519.
* @param args.legacy - Indicates whether to use the legacy account generation method. Defaults to true.
*/
static generate(args?: GenerateEd25519AccountArgs): Ed25519Account;
static generate(args: GenerateEd25519SingleKeyAccountArgs): SingleKeyAccount;
static generate(args: GenerateSingleKeyAccountArgs): SingleKeyAccount;
static generate(args: GenerateAccountArgs): Account$1;
/**
* Creates an account from a given private key and address.
* This function allows you to instantiate an account based on the provided private key,
* and it can differentiate between legacy and non-legacy accounts.
*
* @param args - The arguments for creating the account.
* @param args.privateKey - The private key used to create the account.
* @param args.address - The address associated with the account.
* @param args.legacy - A boolean indicating whether to create a legacy account (default is true).
* @returns An instance of either Ed25519Account or SingleKeyAccount based on the provided private key.
*/
static fromPrivateKey(args: CreateEd25519AccountFromPrivateKeyArgs): Ed25519Account;
static fromPrivateKey(args: CreateEd25519SingleKeyAccountFromPrivateKeyArgs): SingleKeyAccount;
static fromPrivateKey(args: CreateSingleKeyAccountFromPrivateKeyArgs): SingleKeyAccount;
static fromPrivateKey(args: CreateAccountFromPrivateKeyArgs): Account$1;
/**
* @deprecated use `fromPrivateKey` instead.
* Instantiates an account using a private key and a specified account address. This is primarily used to instantiate an
* `Account` that has had its authentication key rotated.
*
* @param args - The arguments required to create an account from a private key.
* @param args.privateKey - The underlying private key for the account.
* @param args.address - The account address the `Account` will sign for.
* @param args.legacy - Optional. If set to false, the keypair generated is a Unified keypair. Defaults to generating a Legacy
* Ed25519 keypair.
*
* @returns Account
*/
static fromPrivateKeyAndAddress(args: CreateAccountFromPrivateKeyArgs): Account$1;
/**
* Generates an account from a specified derivation path and mnemonic.
* This function allows you to create an account using different signing schemes based on the provided arguments.
*
* @param args - The arguments for generating the account.
* @param args.scheme - The signing scheme to use for account generation. Defaults to Ed25519.
* @param args.mnemonic - The mnemonic phrase used to derive the account.
* @param args.path - The derivation path used to generate the account.
* @param args.legacy - A boolean indicating whether to use the legacy account generation method. Defaults to true.
*/
static fromDerivationPath(args: GenerateEd25519AccountArgs & PrivateKeyFromDerivationPathArgs): Ed25519Account;
static fromDerivationPath(args: GenerateEd25519SingleKeyAccountArgs & PrivateKeyFromDerivationPathArgs): SingleKeyAccount;
static fromDerivationPath(args: GenerateSingleKeyAccountArgs & PrivateKeyFromDerivationPathArgs): SingleKeyAccount;
static fromDerivationPath(args: GenerateAccountArgs & PrivateKeyFromDerivationPathArgs): Account$1;
/**
* Retrieve the authentication key for the associated account using the provided public key.
* This key enables account owners to rotate their private key(s) associated with the account without changing the address that
* hosts their account.
* See here for more info: {@link https://aptos.dev/concepts/accounts#single-signer-authentication}
*
* @param args - The arguments for retrieving the authentication key.
* @param args.publicKey - The public key of the account.
* @returns The authentication key for the associated account.
*/
static authKey(args: {
publicKey: AccountPublicKey;
}): AuthenticationKey;
/**
* Sign a message using the available signing capabilities.
* @param message the signing message, as binary input
* @return the AccountAuthenticator containing the signature, together with the account's public key
*/
abstract signWithAuthenticator(message: HexInput): AccountAuthenticator;
/**
* Sign a transaction using the available signing capabilities.
* @param transaction the raw transaction
* @return the AccountAuthenticator containing the signature of the transaction, together with the account's public key
*/
abstract signTransactionWithAuthenticator(transaction: AnyRawTransaction): AccountAuthenticator;
/**
* Sign the given message using the available signing capabilities.
* @param message in HexInput format
* @returns Signature
*/
abstract sign(message: HexInput): Signature;
/**
* Sign the given transaction using the available signing capabilities.
* @param transaction the transaction to be signed
* @returns Signature
*/
abstract signTransaction(transaction: AnyRawTransaction): Signature;
/**
* Verify the given message and signature with the public key.
* This function helps ensure the integrity and authenticity of a message by validating its signature.
*
* @param args - The arguments for verifying the signature.
* @param args.message - The raw message data in HexInput format.
* @param args.signature - The signed message signature.
* @returns A boolean indicating whether the signature is valid.
*/
verifySignature(args: VerifySignatureArgs): boolean;
}
/**
* Arguments required to create an instance of an Ed25519 signer.
*
* @param privateKey - The private key used for signing.
* @param address - Optional account address associated with the signer.
*/
interface Ed25519SignerConstructorArgs {
privateKey: Ed25519PrivateKey;
address?: AccountAddressInput;
}
/**
* Arguments for creating an Ed25519 signer from a derivation path.
*
* @param path - The derivation path for the Ed25519 key.
* @param mnemonic - The mnemonic phrase used to generate the key.
*/
interface Ed25519SignerFromDerivationPathArgs {
path: string;
mnemonic: string;
}
/**
* Arguments required to verify an Ed25519 signature against a given message.
*
* @param message - The message to be verified, represented in hexadecimal format.
* @param signature - The Ed25519 signature to validate.
*/
interface VerifyEd25519SignatureArgs {
message: HexInput;
signature: Ed25519Signature;
}
/**
* Represents an Ed25519 account that provides signing capabilities through an Ed25519 private key.
* This class allows for the creation of accounts, signing messages and transactions, and verifying signatures.
*
* Note: Generating an instance of this class does not create the account on-chain.
*/
declare class Ed25519Account implements Account$1 {
/**
* Private key associated with the account
*/
readonly privateKey: Ed25519PrivateKey;
readonly publicKey: Ed25519PublicKey;
readonly accountAddress: AccountAddress;
readonly signingScheme = SigningScheme.Ed25519;
/**
* Creates an instance of the Ed25519Signer with the specified parameters.
* This constructor initializes the private key, public key, and account address for the signer.
*
* @param args - The constructor arguments for the Ed25519Signer.
* @param args.privateKey - The private key used for signing.
* @param args.address - The optional account address; if not provided, it will derive the address from the public key.
*/
constructor(args: Ed25519SignerConstructorArgs);
/**
* Generates a new Ed25519 account using a randomly generated private key.
* This function is useful for creating a signer that can be used for cryptographic operations.
*
* @returns {Ed25519Account} The newly generated Ed25519 account.
*/
static generate(): Ed25519Account;
/**
* Derives an Ed25519 account using a specified BIP44 path and mnemonic seed phrase.
*
* @param args - The arguments for deriving the account.
* @param args.path - The BIP44 derive hardened path, e.g., m/44'/637'/0'/0'/0'.
* Detailed description: {@link https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki}
* @param args.mnemonic - The mnemonic seed phrase of the account.
*/
static fromDerivationPath(args: Ed25519SignerFromDerivationPathArgs): Ed25519Account;
/**
* Verify the given message and signature with the public key.
*
* @param args - The arguments for verifying the signature.
* @param args.message - Raw message data in HexInput format.
* @param args.signature - Signed message signature.
* @returns A boolean indicating whether the signature is valid.
*/
verifySignature(args: VerifyEd25519SignatureArgs): boolean;
/**
* Sign a message using the account's Ed25519 private key.
* This function returns an AccountAuthenticator containing the signature along with the account's public key.
*
* @param message - The signing message, represented as hexadecimal input.
* @returns An AccountAuthenticator containing the signature and the account's public key.
*/
signWithAuthenticator(message: HexInput): AccountAuthenticatorEd25519;
/**
* Sign a transaction using the account's Ed25519 private key.
* This function returns an AccountAuthenticator that contains the signature of the transaction along with the account's public key.
*
* @param transaction - The raw transaction to be signed.
* @returns An AccountAuthenticator containing the signature and the public key.
*/
signTransactionWithAuthenticator(transaction: AnyRawTransaction): AccountAuthenticatorEd25519;
/**
* Sign the given message using the account's Ed25519 private key.
* @param message - The message to be signed in HexInput format.
* @returns Signature - The resulting signature of the signed message.
*/
sign(message: HexInput): Ed25519Signature;
/**
* Sign the given transaction using the available signing capabilities.
* This function helps ensure that the transaction is properly authenticated before submission.
*
* @param transaction - The transaction to be signed.
* @returns Signature - The resulting signature for the transaction.
*/
signTransaction(transaction: AnyRawTransaction): Ed25519Signature;
}
/**
* Represents an ephemeral key pair used for signing transactions via the Keyless authentication scheme.
* This key pair is temporary and includes an expiration time.
* For more details on how this class is used, refer to the documentation:
* https://aptos.dev/guides/keyless-accounts/#1-present-the-user-with-a-sign-in-with-idp-button-on-the-ui
*/
declare class EphemeralKeyPair extends Serializable {
static readonly BLINDER_LENGTH: number;
/**
* A byte array of length BLINDER_LENGTH used to obfuscate the public key from the IdP.
* Used in calculating the nonce passed to the IdP and as a secret witness in proof generation.
*/
readonly blinder: Uint8Array;
/**
* A timestamp in seconds indicating when the ephemeral key pair is expired. After expiry, a new
* EphemeralKeyPair must be generated and a new JWT needs to be created.
*/
readonly expiryDateSecs: number;
/**
* The value passed to the IdP when the user authenticates. It consists of a hash of the
* ephemeral public key, expiry date, and blinder.
*/
readonly nonce: string;
/**
* A private key used to sign transactions. This private key is not tied to any account on the chain as it
* is ephemeral (not permanent) in nature.
*/
private privateKey;
/**
* A public key used to verify transactions. This public key is not tied to any account on the chain as it
* is ephemeral (not permanent) in nature.
*/
private publicKey;
/**
* Creates an instance of the class with a specified private key, optional expiry date, and optional blinder.
* This constructor initializes the public key, sets the expiry date to a default value if not provided,
* generates a blinder if not supplied, and calculates the nonce based on the public key, expiry date, and blinder.
*
* @param args - The parameters for constructing the instance.
* @param args.privateKey - The private key used for creating the instance.
* @param args.expiryDateSecs - Optional expiry date in seconds from the current time. Defaults to two weeks from now.
* @param args.blinder - Optional blinder value. If not provided, a new blinder will be generated.
*/
constructor(args: {
privateKey: PrivateKey;
expiryDateSecs?: number;
blinder?: HexInput;
});
/**
* Returns the public key of the key pair.
* @return EphemeralPublicKey
*/
getPublicKey(): EphemeralPublicKey;
/**
* Checks if the current time has surpassed the expiry date of the key pair.
* @return boolean - Returns true if the key pair is expired, otherwise false.
*/
isExpired(): boolean;
/**
* Serializes the object's properties into a format suitable for transmission or storage.
* This function is essential for preparing the object data for serialization processes.
*
* @param serializer - The serializer instance used to serialize the object's properties.
*/
serialize(serializer: Serializer): void;
/**
* Deserializes an ephemeral key pair from the provided deserializer.
* This function helps in reconstructing an ephemeral key pair, which is essential for cryptographic operations.
*
* @param deserializer - The deserializer instance used to read the serialized data.
*/
static deserialize(deserializer: Deserializer): EphemeralKeyPair;
/**
* Deserialize a byte array into an EphemeralKeyPair object.
* This function allows you to reconstruct an EphemeralKeyPair from its serialized byte representation.
*
* @param bytes - The byte array representing the serialized EphemeralKeyPair.
*/
static fromBytes(bytes: Uint8Array): EphemeralKeyPair;
/**
* Generates a new ephemeral key pair with an optional expiry date.
* This function allows you to create a temporary key pair for secure operations.
*
* @param args - Optional parameters for key pair generation.
* @param args.scheme - The type of key pair to use for the EphemeralKeyPair. Only Ed25519 is supported for now.
* @param args.expiryDateSecs - The date of expiry for the key pair in seconds.
* @returns An instance of EphemeralKeyPair containing the generated private key and expiry date.
*/
static generate(args?: {
scheme?: EphemeralPublicKeyVariant;
expiryDateSecs?: number;
}): EphemeralKeyPair;
/**
* Sign the given data using the private key, returning an ephemeral signature.
* This function is essential for creating a secure signature that can be used for authentication or verification purposes.
*
* @param data - The data to be signed, provided in HexInput format.
* @returns EphemeralSignature - The resulting ephemeral signature.
* @throws Error - Throws an error if the EphemeralKeyPair has expired.
*/
sign(data: HexInput): EphemeralSignature;
}
/**
* An interface which defines if an Account utilizes Keyless signing.
*/
interface KeylessSigner extends Account$1 {
checkKeylessAccountValidity(aptosConfig: AptosConfig): Promise<void>;
}
declare function isKeylessSigner(obj: any): obj is KeylessSigner;
/**
* Account implementation for the Keyless authentication scheme. This abstract class is used for standard Keyless Accounts
* and Federated Keyless Accounts.
*/
declare abstract class AbstractKeylessAccount extends Serializable implements KeylessSigner {
static readonly PEPPER_LENGTH: number;
/**
* The KeylessPublicKey associated with the account
*/
readonly publicKey: KeylessPublicKey | FederatedKeylessPublicKey;
/**
* The EphemeralKeyPair used to generate sign.
*/
readonly ephemeralKeyPair: EphemeralKeyPair;
/**
* The claim on the JWT to identify a user. This is typically 'sub' or 'email'.
*/
readonly uidKey: string;
/**
* The value of the uidKey claim on the JWT. This intended to be a stable user identifier.
*/
readonly uidVal: string;
/**
* The value of the 'aud' claim on the JWT, also known as client ID. This is the identifier for the dApp's
* OIDC registration with the identity provider.
*/
readonly aud: string;
/**
* A value contains 31 bytes of entropy that preserves privacy of the account. Typically fetched from a pepper provider.
*/
readonly pepper: Uint8Array;
/**
* Account address associated with the account
*/
readonly accountAddress: AccountAddress;
/**
* The zero knowledge signature (if ready) which contains the proof used to validate the EphemeralKeyPair.
*/
proof: ZeroKnowledgeSig | undefined;
/**
* The proof of the EphemeralKeyPair or a promise that provides the proof. This is used to allow for awaiting on
* fetching the proof.
*/
readonly proofOrPromise: ZeroKnowledgeSig | Promise<ZeroKnowledgeSig>;
/**
* Signing scheme used to sign transactions
*/
readonly signingScheme: SigningScheme;
/**
* The JWT token used to derive the account
*/
readonly jwt: string;
/**
* The hash of the verification key used to verify the proof. This is optional and can be used to check verifying key
* rotations which may invalidate the proof.
*/
readonly verificationKeyHash?: Uint8Array;
/**
* An event emitter used to assist in handling asynchronous proof fetching.
*/
private readonly emitter;
/**
* Use the static generator `create(...)` instead.
* Creates an instance of the KeylessAccount with an optional proof.
*
* @param args - The parameters for creating a KeylessAccount.
* @param args.address - Optional account address associated with the KeylessAccount.
* @param args.publicKey - A KeylessPublicKey or FederatedKeylessPublicKey.
* @param args.ephemeralKeyPair - The ephemeral key pair used in the account creation.
* @param args.iss - A JWT issuer.
* @param args.uidKey - The claim on the JWT to identify a user. This is typically 'sub' or 'email'.
* @param args.uidVal - The unique id for this user, intended to be a stable user identifier.
* @param args.aud - The value of the 'aud' claim on the JWT, also known as client ID. This is the identifier for the dApp's
* OIDC registration with the identity provider.
* @param args.pepper - A hexadecimal input used for additional security.
* @param args.proof - A Zero Knowledge Signature or a promise that resolves to one.
* @param args.proofFetchCallback - Optional callback function for fetching proof.
* @param args.jwt - A JSON Web Token used for authentication.
* @param args.verificationKeyHash Optional 32-byte verification key hash as hex input used to check proof validity.
*/
protected constructor(args: {
address?: AccountAddress;
publicKey: KeylessPublicKey | FederatedKeylessPublicKey;
ephemeralKeyPair: EphemeralKeyPair;
iss: string;
uidKey: string;
uidVal: string;
aud: string;
pepper: HexInput;
proof: ZeroKnowledgeSig | Promise<ZeroKnowledgeSig>;
proofFetchCallback?: ProofFetchCallback;
jwt: string;
verificationKeyHash?: HexInput;
});
/**
* This initializes the asynchronous proof fetch.
* @return Emits whether the proof succeeds or fails, but has no return.
*/
init(promise: Promise<ZeroKnowledgeSig>): Promise<void>;
/**
* Serializes the jwt data into a format suitable for transmission or storage.
* This function ensures that both the jwt data and the proof are properly serialized.
*
* @param serializer - The serializer instance used to convert the jwt data into bytes.
*/
serialize(serializer: Serializer): void;
static partialDeserialize(deserializer: Deserializer): {
address: AccountAddress;
jwt: string;
uidKey: string;
pepper: Uint8Array;
ephemeralKeyPair: EphemeralKeyPair;
proof: ZeroKnowledgeSig;
verificationKeyHash?: Uint8Array;
};
/**
* Checks if the proof is expired. If so the account must be re-derived with a new EphemeralKeyPair
* and JWT token.
* @return boolean
*/
isExpired(): boolean;
/**
* Sign a message using Keyless.
* @param message the message to sign, as binary input
* @return the AccountAuthenticator containing the signature, together with the account's public key
*/
signWithAuthenticator(message: HexInput): AccountAuthenticatorSingleKey;
/**
* Sign a transaction using Keyless.
* @param transaction the raw transaction
* @return the AccountAuthenticator containing the signature of the transaction, together with the account's public key
*/
signTransactionWithAuthenticator(transaction: AnyRawTransaction): AccountAuthenticatorSingleKey;
/**
* Waits for asynchronous proof fetching to finish.
* @return
*/
waitForProofFetch(): Promise<void>;
/**
* Validates that the Keyless Account can be used to sign transactions.
* @return
*/
checkKeylessAccountValidity(aptosConfig: AptosConfig): Promise<void>;
/**
* Sign the given message using Keyless.
* @param message in HexInput format
* @returns Signature
*/
sign(message: HexInput): KeylessSignature;
/**
* Sign the given transaction with Keyless.
* Signs the transaction and proof to guard against proof malleability.
* @param transaction the transaction to be signed
* @returns KeylessSignature
*/
signTransaction(transaction: AnyRawTransaction): KeylessSignature;
/**
* Note - This function is currently incomplete and should only be used to verify ownership of the KeylessAccount
*
* Verifies a signature given the message.
*
* TODO: Groth16 proof verification
*
* @param args.message the message that was signed.
* @param args.signature the KeylessSignature to verify
* @returns boolean
*/
verifySignature(args: {
message: HexInput;
signature: KeylessSignature;
}): boolean;
/**
* Fetches the JWK from the issuer's well-known JWKS endpoint.
*
* @param args.publicKey The keyless public key to query
* @param args.kid The kid of the JWK to fetch
* @returns A JWK matching the `kid` in the JWT header.
* @throws {KeylessError} If the JWK cannot be fetched
*/
static fetchJWK(args: {
aptosConfig: AptosConfig;
publicKey: KeylessPublicKey | FederatedKeylessPublicKey;
kid: string;
}): Promise<MoveJWK>;
}
/**
* A container class to hold a transaction and a proof. It implements CryptoHashable which is used to create
* the signing message for Keyless transactions. We sign over the proof to ensure non-malleability.
*/
declare class TransactionAndProof extends Serializable {
/**
* The transaction to sign.
*/
transaction: AnyRawTransactionInstance;
/**
* The zero knowledge proof used in signing the transaction.
*/
proof?: ZkProof;
/**
* The domain separator prefix used when hashing.
*/
readonly domainSeparator = "APTOS::TransactionAndProof";
constructor(transaction: AnyRawTransactionInstance, proof?: ZkProof);
/**
* Serializes the transaction data into a format suitable for transmission or storage.
* This function ensures that both the transaction bytes and the proof are properly serialized.
*
* @param serializer - The serializer instance used to convert the transaction data into bytes.
*/
serialize(serializer: Serializer): void;
/**
* Hashes the bcs serialized from of the class. This is the typescript corollary to the BCSCryptoHash macro in aptos-core.
*
* @returns Uint8Array
*/
hash(): Uint8Array;
}
type ProofFetchSuccess = {
status: "Success";
};
type ProofFetchFailure = {
status: "Failed";
error: string;
};
type ProofFetchStatus = ProofFetchSuccess | ProofFetchFailure;
type ProofFetchCallback = (status: ProofFetchStatus) => Promise<void>;
interface ProofFetchEvents {
proofFetchFinish: (status: ProofFetchStatus) => void;
}
/**
* Account implementation for the Keyless authentication scheme.
*
* Used to represent a Keyless based account and sign transactions with it.
*
* Use `KeylessAccount.create()` to instantiate a KeylessAccount with a JWT, proof and EphemeralKeyPair.
*
* When the proof expires or the JWT becomes invalid, the KeylessAccount must be instantiated again with a new JWT,
* EphemeralKeyPair, and corresponding proof.
*/
declare class KeylessAccount extends AbstractKeylessAccount {
/**
* The KeylessPublicKey associated with the account
*/
readonly publicKey: KeylessPublicKey;
/**
* Use the static generator `create(...)` instead.
* Creates an instance of the KeylessAccount with an optional proof.
*
* @param args - The parameters for creating a KeylessAccount.
* @param args.address - Optional account address associated with the KeylessAccount.
* @param args.ephemeralKeyPair - The ephemeral key pair used in the account creation.
* @param args.iss - A JWT issuer.
* @param args.uidKey - The claim on the JWT to identify a user. This is typically 'sub' or 'email'.
* @param args.uidVal - The unique id for this user, intended to be a stable user identifier.
* @param args.aud - The value of the 'aud' claim on the JWT, also known as client ID. This is the identifier for the dApp's
* OIDC registration with the identity provider.
* @param args.pepper - A hexadecimal input used for additional security.
* @param args.proof - A Zero Knowledge Signature or a promise that resolves to one.
* @param args.proofFetchCallback - Optional callback function for fetching proof.
* @param args.jwt - A JSON Web Token used for authentication.
*/
private constructor();
/**
* Serializes the transaction data into a format suitable for transmission or storage.
* This function ensures that both the transaction bytes and the proof are properly serialized.
*
* @param serializer - The serializer instance used to convert the transaction data into bytes.
*/
serialize(serializer: Serializer): void;
/**
* Deserializes the provided deserializer to create a KeylessAccount instance.
* This function extracts necessary components such as the JWT, UID key, pepper, ephemeral key pair, and proof from the deserializer.
*
* @param deserializer - The deserializer instance used to retrieve the serialized data.
* @returns A KeylessAccount instance created from the deserialized data.
*/
static deserialize(deserializer: Deserializer): KeylessAccount;
/**
* Deserialize bytes using this account's information.
*
* @param bytes The bytes being interpreted.
* @returns
*/
static fromBytes(bytes: HexInput): KeylessAccount;
/**
* Creates a KeylessAccount instance using the provided parameters.
* This function allows you to set up a KeylessAccount with specific attributes such as address, proof, and JWT.
* This is used instead of the KeylessAccount constructor.
*
* @param args - The parameters for creating a KeylessAccount.
* @param args.address - Optional account address associated with the KeylessAccount.
* @param args.proof - A Zero Knowledge Signature or a promise that resolves to one.
* @param args.jwt - A JSON Web Token used for authentication.
* @param args.ephemeralKeyPair - The ephemeral key pair used in the account creation.
* @param args.pepper - A hexadecimal input used for additional security.
* @param args.uidKey - Optional key for user identification, defaults to "sub".
* @param args.proofFetchCallback - Optional callback function for fetching proof.
*/
static create(args: {
address?: AccountAddress;
proof: ZeroKnowledgeSig | Promise<ZeroKnowledgeSig>;
jwt: string;
ephemeralKeyPair: EphemeralKeyPair;
pepper: HexInput;
uidKey?: string;
proofFetchCallback?: ProofFetchCallback;
verificationKey?: Groth16VerificationKey;
}): KeylessAccount;
}
/**
* Account implementation for the FederatedKeyless authentication scheme.
*
* Used to represent a FederatedKeyless based account and sign transactions with it.
*
* Use `FederatedKeylessAccount.create()` to instantiate a KeylessAccount with a JSON Web Token (JWT), proof, EphemeralKeyPair and the
* address the JSON Web Key Set (JWKS) are installed that will be used to verify the JWT.
*
* When the proof expires or the JWT becomes invalid, the KeylessAccount must be instantiated again with a new JWT,
* EphemeralKeyPair, and corresponding proof.
*/
declare class FederatedKeylessAccount extends AbstractKeylessAccount {
/**
* The FederatedKeylessPublicKey associated with the account
*/
readonly publicKey: FederatedKeylessPublicKey;
/**
* Use the static generator `FederatedKeylessAccount.create(...)` instead.
* Creates a KeylessAccount instance using the provided parameters.
* This function allows you to set up a KeylessAccount with specific attributes such as address, proof, and JWT.
*
* @param args - The parameters for creating a KeylessAccount.
* @param args.address - Optional account address associated with the KeylessAccount.
* @param args.proof - A Zero Knowledge Signature or a promise that resolves to one.
* @param args.jwt - A JSON Web Token used for authentication.
* @param args.ephemeralKeyPair - The ephemeral key pair used in the account creation.
* @param args.jwkAddress - The address which stores the JSON Web Key Set (JWKS) used to verify the JWT.
* @param args.uidKey - Optional key for user identification, defaults to "sub".
* @param args.proofFetchCallback - Optional callback function for fetching proof.
*/
private constructor();
/**
* Serializes the transaction data into a format suitable for transmission or storage.
* This function ensures that both the transaction bytes and the proof are properly serialized.
*
* @param serializer - The serializer instance used to convert the transaction data into bytes.
*/
serialize(serializer: Serializer): void;
/**
* Deserializes the provided deserializer to create a KeylessAccount instance.
* This function extracts necessary components such as the JWT, UID key, pepper, ephemeral key pair, and proof from the deserializer.
*
* @param deserializer - The deserializer instance used to retrieve the serialized data.
* @returns A KeylessAccount instance created from the deserialized data.
*/
static deserialize(deserializer: Deserializer): FederatedKeylessAccount;
/**
* Deserialize bytes using this account's information.
*
* @param bytes The bytes being interpreted.
* @returns
*/
static fromBytes(bytes: HexInput): FederatedKeylessAccount;
/**
* Creates a KeylessAccount instance using the provided parameters.
* This function allows you to set up a KeylessAccount with specific attributes such as address, proof, and JWT.
* This is used instead of the KeylessAccount constructor.
*
* @param args - The parameters for creating a KeylessAccount.
* @param args.address - Optional account address associated with the KeylessAccount.
* @param args.proof - A Zero Knowledge Signature or a promise that resolves to one.
* @param args.jwt - A JSON Web Token used for authentication.
* @param args.ephemeralKeyPair - The ephemeral key pair used in the account creation.
* @param args.jwkAddress - The address which stores the JSON Web Key Set (JWKS) used to verify the JWT.
* @param args.uidKey - Optional key for user identification, defaults to "sub".
* @param args.proofFetchCallback - Optional callback function for fetching proof.
*/
static create(args: {
address?: AccountAddress;
proof: ZeroKnowledgeSig | Promise<ZeroKnowledgeSig>;
jwt: string;
ephemeralKeyPair: EphemeralKeyPair;
pepper: HexInput;
jwkAddress: AccountAddressInput;
uidKey?: string;
proofFetchCallback?: ProofFetchCallback;
verificationKey?: Groth16VerificationKey;
}): FederatedKeylessAccount;
}
/**
* Arguments required to verify a multi-key signature against a given message.
*
* @param message - The original message that was signed.
* @param signature - The multi-key signature to be verified.
*/
interface VerifyMultiKeySignatureArgs {
message: HexInput;
signature: MultiKeySignature;
}
/**
* Signer implementation for the MultiKey authentication scheme.
*
* This account utilizes an M of N signing scheme, where M and N are specified in the {@link MultiKey}.
* It signs messages using an array of M accounts, each corresponding to a public key in the {@link MultiKey}.
*
* Note: Generating a signer instance does not create the account on-chain.
*/
declare class MultiKeyAccount implements Account$1, KeylessSigner {
/**
* Public key associated with the account
*/
readonly publicKey: MultiKey;
/**
* Account address associated with the account
*/
readonly accountAddress: AccountAddress;
/**
* Signing scheme used to sign transactions
*/
readonly signingScheme: SigningScheme;
/**
* The signers used to sign messages. These signers should correspond to public keys in the
* MultiKeyAccount's public key. The number of signers should be equal or greater
* than this.publicKey.signaturesRequired
*/
readonly signers: Account$1[];
/**
* An array of indices where for signer[i], signerIndicies[i] is the index of the corresponding public key in
* publicKey.publicKeys. Used to derive the right public key to use for verification.
*/
readonly signerIndicies: number[];
readonly signaturesBitmap: Uint8Array;
/**
* Constructs a MultiKeyAccount instance, which requires multiple signatures for transactions.
*
* @param args - The arguments for creating a MultiKeyAccount.
* @param args.multiKey - The multikey of the account consisting of N public keys and a number M representing the required signatures.
* @param args.signers - An array of M signers that will be used to sign the transaction.
* @param args.address - An optional account address input. If not provided, the derived address from the public key will be used.
*/
constructor(args: {
multiKey: MultiKey;
signers: Account$1[];
address?: AccountAddressInput;
});
/**
* Static constructor to create a MultiKeyAccount using the provided public keys and signers.
*
* @param args - The arguments for creating a MultiKeyAccount.
* @param args.publicKeys - The N public keys of the MultiKeyAccount.
* @param args.signaturesRequired - The number of signatures required to authorize a transaction.
* @param args.signers - An array of M signers that will be used to sign the transaction.
* @returns MultiKeyAccount - The newly created MultiKeyAccount.
*/
static fromPublicKeysAndSigners(args: {
publicKeys: PublicKey[];
signaturesRequired: number;
signers: Account$1[];
}): MultiKeyAccount;
/**
* Determines if the provided account is a multi-key account.
*
* @param account - The account to check.
* @returns A boolean indicating whether the account is a multi-key account.
*/
static isMultiKeySigner(account: Account$1): account is MultiKeyAccount;
/**
* Sign a message using the account's signers and return an AccountAuthenticator containing the signature along with the
* account's public key.
* @param message - The signing message, represented as binary input in hexadecimal format.
* @returns An instance of AccountAuthenticatorMultiKey that includes the signature and the public key.
*/
signWithAuthenticator(message: HexInput): AccountAuthenticatorMultiKey;
/**
* Sign a transaction using the account's signers, returning an AccountAuthenticator that contains the signature and the
* account's public key.
* @param transaction - The raw transaction to be signed.
* @returns An AccountAuthenticatorMultiKey containing the signature of the transaction along with the account's public key.
*/
signTransactionWithAuthenticator(transaction: AnyRawTransaction): AccountAuthenticatorMultiKey;
/**
* Waits for any proofs on KeylessAccount signers to be fetched. This ensures that signing with the KeylessAccount does not
* fail due to missing proofs.
* @return {Promise<void>} A promise that resolves when all proofs have been fetched.
*/
waitForProofFetch(): Promise<void>;
/**
* Validates that the Keyless Account can be used to sign transactions.
* @return
*/
checkKeylessAccountValidity(aptosConfig: AptosConfig): Promise<void>;
/**
* Sign the given message using the MultiKeyAccount's signers
* @param message in HexInput format
* @returns MultiKeySignature
*/
sign(data: HexInput): MultiKeySignature;
/**
* Sign the given transaction using the MultiKeyAccount's signers.
* This function aggregates signatures from all signers associated with the MultiKeyAccount.
*
* @param transaction - The transaction to be signed.
* @returns MultiKeySignature - An object containing the aggregated signatures and a bitmap of the signatures.
*/
signTransaction(transaction: AnyRawTransaction): MultiKeySignature;
/**
* Verify the given message and signature with the public keys.
*
* This function checks if the provided signatures are valid for the given message using the corresponding public keys.
*
* @param args - The arguments for verifying the signature.
* @param args.message - The raw message data in HexInput format.
* @param args.signature - The signed message MultiKeySignature containing multiple signatures.
* @returns A boolean indicating whether the signatures are valid for the message.
*/
verifySignature(args: VerifyMultiKeySignatureArgs): boolean;
}
/**
* A class to query all `Account` related queries on Aptos.
*/
declare class Account {
readonly config: AptosConfig;
/**
* Creates an instance of the Aptos client with the provided configuration.
*
* @param config - The configuration settings for the Aptos client.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* async function runExample() {
* // Initialize the Aptos client with testnet configuration
* const config = new AptosConfig({ network: Network.TESTNET }); // specify your own network if needed
* const aptos = new Aptos(config);
*
* console.log("Aptos client initialized:", aptos);
* }
* runExample().catch(console.error);
* ```
*/
constructor(config: AptosConfig);
/**
* Queries the current state for an Aptos account given its account address.
*
* @param args - The arguments for retrieving account information.
* @param args.accountAddress - The Aptos account address to query.
* @returns The account data.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Retrieve account information for a specific address
* const accountInfo = await aptos.getAccountInfo({ accountAddress: "0x1" }); // replace with a real account address
* console.log(accountInfo);
* }
* runExample().catch(console.error);
* ```
*/
getAccountInfo(args: {
accountAddress: AccountAddressInput;
}): Promise<AccountData>;
/**
* Queries for all modules in an account given an account address.
* This function may call the API multiple times to auto paginate through results.
*
* @param args.accountAddress - The Aptos account address to query modules for.
* @param args.options.offset - The number of modules to start returning results from.
* @param args.options.limit - The maximum number of results to return.
* @param args.options.ledgerVersion - The ledger version to query; if not provided, it retrieves the latest version.
*
* @returns - The account modules associated with the specified address.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Fetching account modules for a specific account
* const accountModules = await aptos.getAccountModules({
* accountAddress: "0x1", // replace with a real account address
* options: {
* offset: 0, // starting from the first module
* limit: 10, // limiting to 10 modules
* },
* });
*
* console.log(accountModules);
* }
* runExample().catch(console.error);
* ```
*/
getAccountModules(args: {
accountAddress: AccountAddressInput;
options?: PaginationArgs & LedgerVersionArg;
}): Promise<MoveModuleBytecode[]>;
/**
* Queries for a specific account module given an account address and module name.
*
* @param args.accountAddress - The Aptos account address.
* @param args.moduleName - The name of the module.
* @param args.options.ledgerVersion - The ledger version to query; if not provided, it will get the latest version.
*
* @returns The account module associated with the specified account address and module name.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Get the account module for a specific account address and module name
* const module = await aptos.getAccountModule({
* accountAddress: "0x1", // replace with a real account address
* moduleName: "MyModule" // specify the module name
* });
*
* console.log(module);
* }
* runExample().catch(console.error);
* ```
*/
getAccountModule(args: {
accountAddress: AccountAddressInput;
moduleName: string;
options?: LedgerVersionArg;
}): Promise<MoveModuleBytecode>;
/**
* Queries account transactions given an account address.
* This function may call the API multiple times to auto paginate and retrieve all account transactions.
*
* @param args.accountAddress - The Aptos account address to query transactions for.
* @param args.options - Optional pagination arguments.
* @param args.options.offset - The number of transactions to start returning results from.
* @param args.options.limit - The maximum number of results to return.
*
* @returns The account transactions.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Fetch transactions for a specific account
* const transactions = await aptos.getAccountTransactions({
* accountAddress: "0x1", // replace with a real account address
* options: {
* offset: 0, // starting from the first transaction
* limit: 10, // limiting to 10 transactions
* },
* });
*
* console.log(transactions);
* }
* runExample().catch(console.error);
* ```
*/
getAccountTransactions(args: {
accountAddress: AccountAddressInput;
options?: PaginationArgs;
}): Promise<TransactionResponse[]>;
/**
* Queries all account resources given an account address.
* This function may call the API multiple times to auto paginate through results.
*
* @param args.accountAddress - The Aptos account address to query resources for.
* @param args.options.offset - The number of resources to start returning results from.
* @param args.options.limit - The maximum number of results to return.
* @param args.options.ledgerVersion - The ledger version to query; if not provided, it will get the latest version.
* @returns Account resources.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Fetching account resources for a specific account address
* const resources = await aptos.getAccountResources({ accountAddress: "0x1" }); // replace with a real account address
* console.log(resources);
* }
* runExample().catch(console.error);
* ```
*/
getAccountResources(args: {
accountAddress: AccountAddressInput;
options?: PaginationArgs & LedgerVersionArg;
}): Promise<MoveResource[]>;
/**
* Queries a specific account resource given an account address and resource type.
*
* @template T - The typed output of the resource.
* @param args.accountAddress - The Aptos account address to query.
* @param args.resourceType - The string representation of an on-chain Move struct type, e.g., "0x1::aptos_coin::AptosCoin".
* @param args.options.ledgerVersion - The ledger version to query; if not provided, it will get the latest version.
* @returns The account resource of the specified type.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Get the account resource for a specific account address and resource type
* const resource = await aptos.getAccountResource({
* accountAddress: "0x1", // replace with a real account address
* resourceType: "0x1::aptos_coin::AptosCoin"
* });
*
* console.log(resource);
* }
* runExample().catch(console.error);
* ```
*/
getAccountResource<T extends {} = any>(args: {
accountAddress: AccountAddressInput;
resourceType: MoveStructId;
options?: LedgerVersionArg;
}): Promise<T>;
/**
* Looks up the account address for a given authentication key, handling both rotated and non-rotated keys.
*
* @param args.authenticationKey - The authentication key for which to look up the account address.
* @param args.minimumLedgerVersion - Optional ledger version to sync up to before querying.
* @param args.options.ledgerVersion - The ledger version to query; if not provided, it will get the latest version.
* @returns Promise<AccountAddress> - The account address associated with the authentication key.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Look up the original account address for a given authentication key
* const accountAddress = await aptos.lookupOriginalAccountAddress({
* authenticationKey: "0x1", // replace with a real authentication key
* });
*
* console.log("Original Account Address:", accountAddress);
* }
* runExample().catch(console.error);
* ```
*/
lookupOriginalAccountAddress(args: {
authenticationKey: AccountAddressInput;
minimumLedgerVersion?: AnyNumber;
options?: LedgerVersionArg;
}): Promise<AccountAddress>;
/**
* Queries the current count of tokens owned by a specified account.
*
* @param args - The parameters for the query.
* @param args.accountAddress - The account address to query the token count for.
* @param args.minimumLedgerVersion - Optional ledger version to sync up to before querying.
* @returns The current count of tokens owned by the account.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Get the count of tokens owned by the account
* const tokensCount = await aptos.getAccountTokensCount({ accountAddress: "0x1" }); // replace with a real account address
* console.log(`Tokens Count: ${tokensCount}`);
* }
* runExample().catch(console.error);
* ```
*/
getAccountTokensCount(args: {
accountAddress: AccountAddressInput;
minimumLedgerVersion?: AnyNumber;
}): Promise<number>;
/**
* Queries the tokens currently owned by a specified account, including NFTs and fungible tokens.
* If desired, you can filter the results by a specific token standard.
*
* @param args.accountAddress The account address for which to retrieve owned tokens.
* @param args.minimumLedgerVersion Optional ledger version to sync up to before querying.
* @param args.options.tokenStandard Optional filter for the NFT standard to query for.
* @param args.options.offset Optional number to start returning results from.
* @param args.options.limit Optional number of results to return.
* @param args.options.orderBy Optional order to sort the tokens by.
* @returns An array of tokens with their respective data.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Get the tokens owned by a specific account
* const accountOwnedTokens = await aptos.getAccountOwnedTokens({
* accountAddress: "0x1", // replace with a real account address
* options: {
* limit: 10, // specify how many tokens to return
* orderBy: "created_at", // specify the order of the results
* },
* });
*
* console.log(accountOwnedTokens);
* }
* runExample().catch(console.error);
* ```
*/
getAccountOwnedTokens(args: {
accountAddress: AccountAddressInput;
minimumLedgerVersion?: AnyNumber;
options?: TokenStandardArg & PaginationArgs & OrderByArg<GetAccountOwnedTokensQueryResponse[0]>;
}): Promise<GetAccountOwnedTokensQueryResponse>;
/**
* Queries all current tokens of a specific collection that an account owns by the collection address.
* This query returns all tokens (v1 and v2 standards) an account owns, including NFTs, fungible, soulbound, etc.
* If you want to get only the token from a specific standard, you can pass an optional tokenStandard parameter.
*
* @param args.accountAddress - The account address we want to get the tokens for.
* @param args.collectionAddress - The address of the collection being queried.
* @param args.minimumLedgerVersion - Optional ledger version to sync up to, before querying.
* @param args.options.tokenStandard - The NFT standard to query for.
* @param args.options.offset - The number token to start returning results from.
* @param args.options.limit - The number of results to return.
* @param args.options.orderBy - The order to sort the tokens by.
* @returns Tokens array with the token data.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Get tokens owned by a specific account in a specific collection
* const accountOwnedTokens = await aptos.getAccountOwnedTokensFromCollectionAddress({
* accountAddress: "0x1", // replace with a real account address
* collectionAddress: "0x2", // replace with a real collection address
* });
*
* console.log(accountOwnedTokens);
* }
* runExample().catch(console.error);
* ```
*/
getAccountOwnedTokensFromCollectionAddress(args: {
accountAddress: AccountAddressInput;
collectionAddress: AccountAddressInput;
minimumLedgerVersion?: AnyNumber;
options?: TokenStandardArg & PaginationArgs & OrderByArg<GetAccountOwnedTokensFromCollectionResponse[0]>;
}): Promise<GetAccountOwnedTokensFromCollectionResponse>;
/**
* Queries for all collections that an account currently has tokens for, including NFTs, fungible tokens, and soulbound tokens.
* If you want to filter by a specific token standard, you can pass an optional tokenStandard parameter.
*
* @param args.accountAddress - The account address we want to get the collections for.
* @param args.minimumLedgerVersion - Optional ledger version to sync up to before querying.
* @param args.options.tokenStandard - The NFT standard to query for.
* @param args.options.offset - The number of the collection to start returning results from.
* @param args.options.limit - The number of results to return.
* @param args.options.orderBy - The order to sort the tokens by.
* @returns Collections array with the collections data.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Get account collections with owned tokens for a specific account
* const accountCollectionsWithOwnedTokens = await aptos.getAccountCollectionsWithOwnedTokens({
* accountAddress: "0x1", // replace with a real account address
* options: {
* tokenStandard: "NFT", // specify the token standard if needed
* limit: 10, // specify the number of results to return
* },
* });
*
* console.log(accountCollectionsWithOwnedTokens);
* }
* runExample().catch(console.error);
* ```
*/
getAccountCollectionsWithOwnedTokens(args: {
accountAddress: AccountAddressInput;
minimumLedgerVersion?: AnyNumber;
options?: TokenStandardArg & PaginationArgs & OrderByArg<GetAccountCollectionsWithOwnedTokenResponse[0]>;
}): Promise<GetAccountCollectionsWithOwnedTokenResponse>;
/**
* Queries the current count of transactions submitted by an account.
*
* @param args - The parameters for the query.
* @param args.accountAddress - The account address we want to get the total count for.
* @param args.minimumLedgerVersion - Optional ledger version to sync up to before querying.
* @returns Current count of transactions made by an account.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Get the count of transactions for a specific account
* const accountTransactionsCount = await aptos.getAccountTransactionsCount({
* accountAddress: "0x1", // replace with a real account address
* minimumLedgerVersion: 1, // specify your own minimum ledger version if needed
* });
*
* console.log(accountTransactionsCount);
* }
* runExample().catch(console.error);
* ```
*/
getAccountTransactionsCount(args: {
accountAddress: AccountAddressInput;
minimumLedgerVersion?: AnyNumber;
}): Promise<number>;
/**
* Retrieves the coins data for a specified account.
*
* @param args.accountAddress - The account address for which to retrieve the coin's data.
* @param args.minimumLedgerVersion - Optional ledger version to sync up to before querying.
* @param args.options.offset - Optional. The number of coins to start returning results from.
* @param args.options.limit - Optional. The number of results to return.
* @param args.options.orderBy - Optional. The order to sort the coins by.
* @param args.options.where - Optional. Filter the results by specific criteria.
* @returns An array containing the coins data for the specified account.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Fetching coins data for a specific account
* const accountCoinsData = await aptos.getAccountCoinsData({
* accountAddress: "0x1", // replace with a real account address
* options: {
* limit: 10, // specify the number of results to return
* orderBy: { asset_type: "asc" }, // specify the order of results
* },
* });
*
* console.log(accountCoinsData);
* }
* runExample().catch(console.error);
* ```
*/
getAccountCoinsData(args: {
accountAddress: AccountAddressInput;
minimumLedgerVersion?: AnyNumber;
options?: PaginationArgs & OrderByArg<GetAccountCoinsDataResponse[0]> & WhereArg<CurrentFungibleAssetBalancesBoolExp>;
}): Promise<GetAccountCoinsDataResponse>;
/**
* Retrieves the current count of an account's coins aggregated across all types.
*
* @param args The parameters for the account coins count query.
* @param args.accountAddress The account address we want to get the total count for.
* @param args.minimumLedgerVersion Optional ledger version to sync up to before querying.
* @returns The current count of the aggregated coins for the specified account.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Getting the account coins count for a specific account
* const accountCoinsCount = await aptos.getAccountCoinsCount({ accountAddress: "0x1" }); // replace with a real account address
* console.log("Account Coins Count:", accountCoinsCount);
* }
* runExample().catch(console.error);
* ```
*/
getAccountCoinsCount(args: {
accountAddress: AccountAddressInput;
minimumLedgerVersion?: AnyNumber;
}): Promise<number>;
/**
* Retrieves the current amount of APT for a specified account.
*
* @param args The arguments for the account query.
* @param args.accountAddress The account address for which to retrieve the APT amount.
* @param args.minimumLedgerVersion Optional ledger version to sync up to before querying.
* @returns The current amount of APT for the specified account.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Get the APT amount for a specific account
* const accountAPTAmount = await aptos.getAccountAPTAmount({ accountAddress: "0x1" }); // replace with a real account address
* console.log("Account APT Amount:", accountAPTAmount);
* }
* runExample().catch(console.error);
* ```
*/
getAccountAPTAmount(args: {
accountAddress: AccountAddressInput;
minimumLedgerVersion?: AnyNumber;
}): Promise<number>;
/**
* Queries the current amount of a specified coin held by an account.
*
* @param args The parameters for querying the account's coin amount.
* @param args.accountAddress The account address to query for the coin amount.
* @param args.coinType The coin type to query. Note: If not provided, it may be automatically populated if `faMetadataAddress`
* is specified.
* @param args.faMetadataAddress The fungible asset metadata address to query. Note: If not provided, it may be automatically
* populated if `coinType` is specified.
* @param args.minimumLedgerVersion Not used anymore, here for backward compatibility
* see https://github.com/aptos-labs/aptos-ts-sdk/pull/519, will be removed in the near future.
* Optional ledger version to sync up to before querying.
* @returns The current amount of the specified coin held by the account.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Query the account's coin amount for a specific coin type
* const accountCoinAmount = await aptos.getAccountCoinAmount({
* accountAddress: "0x1", // replace with a real account address
* coinType: "0x1::aptos_coin::AptosCoin" // specify the coin type
* });
*
* console.log(`Account coin amount: ${accountCoinAmount}`);
* }
* runExample().catch(console.error);
* ```
*/
getAccountCoinAmount(args: {
accountAddress: AccountAddressInput;
coinType?: MoveStructId;
faMetadataAddress?: AccountAddressInput;
minimumLedgerVersion?: AnyNumber;
}): Promise<number>;
/**
* Queries an account's owned objects.
*
* @param args.accountAddress The account address we want to get the objects for.
* @param args.minimumLedgerVersion Optional ledger version to sync up to before querying.
* @param args.options.offset The starting position to start returning results from.
* @param args.options.limit The number of results to return.
* @param args.options.orderBy The order to sort the objects by.
* @returns Objects array with the object data.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Get the objects owned by the specified account
* const accountOwnedObjects = await aptos.getAccountOwnedObjects({
* accountAddress: "0x1", // replace with a real account address
* minimumLedgerVersion: 1, // optional, specify if needed
* options: {
* offset: 0, // optional, specify if needed
* limit: 10, // optional, specify if needed
* orderBy: "created_at", // optional, specify if needed
* },
* });
*
* console.log(accountOwnedObjects);
* }
* runExample().catch(console.error);
* ```
*/
getAccountOwnedObjects(args: {
accountAddress: AccountAddressInput;
minimumLedgerVersion?: AnyNumber;
options?: PaginationArgs & OrderByArg<GetObjectDataQueryResponse[0]>;
}): Promise<GetObjectDataQueryResponse>;
/**
* Derives an account by providing a private key. This function resolves the provided private key type and derives the public
* key from it.
*
* If the privateKey is a Secp256k1 type, it derives the account using the derived public key and auth key using the SingleKey
* scheme locally.
* If the privateKey is an ED25519 type, it looks up the authentication key on chain to determine whether it is a Legacy ED25519
* key or a Unified ED25519 key, and then derives the account based on that.
*
* @param args - The arguments for deriving the account.
* @param args.privateKey - An account private key.
* @returns The derived Account type.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network, Ed25519PrivateKey } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Deriving an account from a private key
* const account = await aptos.deriveAccountFromPrivateKey({
* privateKey: new Ed25519PrivateKey("0x123") // replace with a real private key
* });
*
* console.log(account);
* }
* runExample().catch(console.error);
* ```
*/
deriveAccountFromPrivateKey(args: {
privateKey: PrivateKey;
}): Promise<Account$1>;
}
/**
* A class to handle all `Coin` operations.
*/
declare class Coin {
readonly config: AptosConfig;
/**
* Initializes a new instance of the Aptos client with the specified configuration.
* This allows you to interact with the Aptos blockchain using the provided settings.
*
* @param config - The configuration settings for the Aptos client.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* async function runExample() {
* // Create a new Aptos client with testnet configuration
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* console.log("Aptos client initialized:", aptos);
* }
* runExample().catch(console.error);
* ```
*/
constructor(config: AptosConfig);
/**
* Generate a transfer coin transaction that can be simulated, signed, and submitted.
* This function helps you create a transaction to transfer a specified amount of coins
* from one account to another within the Aptos network.
*
* @param args The arguments for the transfer transaction.
* @param args.sender The sender account address.
* @param args.recipient The recipient account address.
* @param args.amount The amount of coins to transfer.
* @param args.coinType Optional. The coin struct type to transfer. Defaults to 0x1::aptos_coin::AptosCoin.
* @param args.options Optional. Additional options for generating the transaction.
*
* @returns SimpleTransaction
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Generate a transfer coin transaction
* const transaction = await aptos.transferCoinTransaction({
* sender: "0x1", // replace with a real sender account address
* recipient: "0x2", // replace with a real recipient account address
* amount: 10,
* });
*
* console.log(transaction);
* }
* runExample().catch(console.error);
* ```
*/
transferCoinTransaction(args: {
sender: AccountAddressInput;
recipient: AccountAddressInput;
amount: AnyNumber;
coinType?: MoveStructId;
options?: InputGenerateTransactionOptions;
}): Promise<SimpleTransaction>;
}
/**
* This file contains the underlying implementations for exposed API surface in
* the {@link api/digitalAsset}. By moving the methods out into a separate file,
* other namespaces and processes can access these methods without depending on the entire
* digitalAsset namespace and without having a dependency cycle error.
*/
declare const PropertyTypeMap: {
BOOLEAN: string;
U8: string;
U16: string;
U32: string;
U64: string;
U128: string;
U256: string;
ADDRESS: string;
STRING: string;
ARRAY: string;
};
/**
* The keys of the PropertyTypeMap, representing different property types.
*/
type PropertyType = keyof typeof PropertyTypeMap;
/**
* Accepted property value types for user input, including boolean, number, bigint, string, AccountAddress, and Uint8Array.
* To pass in an Array, use Uint8Array type
* for example `new MoveVector([new MoveString("hello"), new MoveString("world")]).bcsToBytes()`
*/
type PropertyValue = boolean | number | bigint | string | AccountAddress | Uint8Array;
/**
* Options for creating a collection, allowing customization of various attributes such as supply limits, mutability of metadata,
* and royalty settings.
*
* @param maxSupply - Maximum number of tokens that can be minted in the collection.
* @param mutableDescription - Indicates if the collection description can be changed after creation.
* @param mutableRoyalty - Indicates if the royalty settings can be modified after creation.
* @param mutableURI - Indicates if the collection URI can be updated.
* @param mutableTokenDescription - Indicates if individual token descriptions can be modified.
* @param mutableTokenName - Indicates if individual token names can be changed.
* @param mutableTokenProperties - Indicates if individual token properties can be altered.
* @param mutableTokenURI - Indicates if individual token URIs can be updated.
* @param tokensBurnableByCreator - Indicates if the creator can burn tokens from the collection.
* @param tokensFreezableByCreator - Indicates if the creator can freeze tokens in the collection.
* @param royaltyNumerator - The numerator for calculating royalties.
* @param royaltyDenominator - The denominator for calculating royalties.
*/
interface CreateCollectionOptions {
maxSupply?: AnyNumber;
mutableDescription?: boolean;
mutableRoyalty?: boolean;
mutableURI?: boolean;
mutableTokenDescription?: boolean;
mutableTokenName?: boolean;
mutableTokenProperties?: boolean;
mutableTokenURI?: boolean;
tokensBurnableByCreator?: boolean;
tokensFreezableByCreator?: boolean;
royaltyNumerator?: number;
royaltyDenominator?: number;
}
/**
* A class to query all `DigitalAsset` related queries on Aptos.
*/
declare class DigitalAsset {
readonly config: AptosConfig;
/**
* Initializes a new instance of the Aptos client with the specified configuration.
* This allows you to interact with the Aptos blockchain using the provided settings.
*
* @param config - The configuration settings for the Aptos client.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* async function runExample() {
* // Create a configuration for the Aptos client
* const config = new AptosConfig({ network: Network.TESTNET }); // Specify your desired network
*
* // Initialize the Aptos client with the configuration
* const aptos = new Aptos(config);
*
* console.log("Aptos client initialized:", aptos);
* }
* runExample().catch(console.error);
* ```
*/
constructor(config: AptosConfig);
/**
* Queries data of a specific collection by the collection creator address and the collection name.
* This function is deprecated; use `getCollectionDataByCreatorAddressAndCollectionName` instead.
*
* If a creator account has two collections with the same name in v1 and v2, you can pass an optional `tokenStandard` parameter
* to query a specific standard.
*
* @param args - The arguments for querying the collection data.
* @param args.creatorAddress - The address of the collection's creator.
* @param args.collectionName - The name of the collection.
* @param args.minimumLedgerVersion - Optional ledger version to sync up to before querying.
* @param args.options - Optional parameters for the query.
* @param args.options.tokenStandard - The token standard to query.
* @returns GetCollectionDataResponse - The response type containing the collection data.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Querying collection data by creator address and collection name
* const collection = await aptos.getCollectionData({
* creatorAddress: "0x1", // replace with a real creator address
* collectionName: "myCollection", // specify your collection name
* });
*
* console.log(collection);
* }
* runExample().catch(console.error);
* ```
*/
getCollectionData(args: {
creatorAddress: AccountAddressInput;
collectionName: string;
minimumLedgerVersion?: AnyNumber;
options?: TokenStandardArg;
}): Promise<GetCollectionDataResponse>;
/**
* Queries data of a specific collection by the collection creator address and the collection name.
* If a creator account has multiple collections with the same name across different versions,
* specify the `tokenStandard` parameter to query a specific standard.
*
* @param args.creatorAddress - The address of the collection's creator.
* @param args.collectionName - The name of the collection.
* @param args.minimumLedgerVersion - Optional ledger version to sync up to before querying.
* @param args.options.tokenStandard - Optional token standard to query.
* @returns GetCollectionDataResponse - The response type containing collection data.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Fetching collection data by creator address and collection name
* const collection = await aptos.getCollectionDataByCreatorAddressAndCollectionName({
* creatorAddress: "0x1", // replace with a real creator address
* collectionName: "myCollection",
* minimumLedgerVersion: 1, // optional, specify if needed
* options: { tokenStandard: "v2" } // optional, specify if needed
* });
*
* console.log(collection);
* }
* runExample().catch(console.error);
* ```
*/
getCollectionDataByCreatorAddressAndCollectionName(args: {
creatorAddress: AccountAddressInput;
collectionName: string;
minimumLedgerVersion?: AnyNumber;
options?: TokenStandardArg & PaginationArgs;
}): Promise<GetCollectionDataResponse>;
/**
* Retrieves data for a specific collection created by a given creator address.
* This function allows you to query collection data while optionally specifying a minimum ledger version and pagination options.
*
* @param args.creatorAddress - The address of the collection's creator.
* @param args.minimumLedgerVersion - Optional ledger version to sync up to before querying.
* @param args.options.tokenStandard - Optional token standard to query.
* @param args.options.pagination - Optional pagination arguments.
* @returns GetCollectionDataResponse - The response type containing collection data.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Retrieve collection data by creator address
* const collectionData = await aptos.getCollectionDataByCreatorAddress({
* creatorAddress: "0x1", // replace with a real creator address
* minimumLedgerVersion: 1, // specify the minimum ledger version if needed
* options: {
* tokenStandard: "v2", // specify the token standard if needed
* pagination: { limit: 10, offset: 0 } // specify pagination options if needed
* }
* });
*
* console.log(collectionData);
* }
* runExample().catch(console.error);
* ```
*/
getCollectionDataByCreatorAddress(args: {
creatorAddress: AccountAddressInput;
minimumLedgerVersion?: AnyNumber;
options?: TokenStandardArg & PaginationArgs;
}): Promise<GetCollectionDataResponse>;
/**
* Queries data of a specific collection by the collection ID.
*
* @param args.collectionId - The ID of the collection, which is the same as the address of the collection object.
* @param args.minimumLedgerVersion - Optional ledger version to sync up to before querying.
* @param args.options - Optional parameters for token standard and pagination.
* @returns GetCollectionDataResponse - The response type containing the collection data.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Fetching collection data by collection ID
* const collection = await aptos.getCollectionDataByCollectionId({
* collectionId: "0x123", // replace with a real collection ID
* });
*
* console.log(collection);
* }
* runExample().catch(console.error);
* ```
*/
getCollectionDataByCollectionId(args: {
collectionId: AccountAddressInput;
minimumLedgerVersion?: AnyNumber;
options?: TokenStandardArg & PaginationArgs;
}): Promise<GetCollectionDataResponse>;
/**
* Queries the ID of a specified collection.
* This ID corresponds to the collection's object address in V2, while V1 does not utilize objects and lacks an address.
*
* @param args.creatorAddress - The address of the collection's creator.
* @param args.collectionName - The name of the collection.
* @param args.minimumLedgerVersion - Optional ledger version to sync up to before querying.
* @param args.options.tokenStandard - The token standard to query.
* @returns The collection ID.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Fetching the collection ID for a specific creator and collection name
* const collectionId = await aptos.getCollectionId({
* creatorAddress: "0x1", // replace with a real creator address
* collectionName: "myCollection"
* });
*
* console.log("Collection ID:", collectionId);
* }
* runExample().catch(console.error);
* ```
*/
getCollectionId(args: {
creatorAddress: AccountAddressInput;
collectionName: string;
minimumLedgerVersion?: AnyNumber;
options?: TokenStandardArg;
}): Promise<string>;
/**
* Retrieves digital asset data using the address of a digital asset.
*
* @param args - The parameters for the request.
* @param args.digitalAssetAddress - The address of the digital asset.
* @param args.minimumLedgerVersion - Optional ledger version to sync up to before querying.
* @returns GetTokenDataResponse containing relevant data for the digital asset.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Fetching digital asset data for a specific address
* const digitalAsset = await aptos.getDigitalAssetData({
* digitalAssetAddress: "0x123", // replace with a real digital asset address
* });
*
* console.log(digitalAsset);
* }
* runExample().catch(console.error);
* ```
*/
getDigitalAssetData(args: {
digitalAssetAddress: AccountAddressInput;
minimumLedgerVersion?: AnyNumber;
}): Promise<GetTokenDataResponse>;
/**
* Retrieves the current ownership data of a specified digital asset using its address.
*
* @param args The parameters for the request.
* @param args.digitalAssetAddress The address of the digital asset.
* @param args.minimumLedgerVersion Optional ledger version to sync up to before querying.
*
* @returns GetCurrentTokenOwnershipResponse containing relevant ownership data of the digital asset.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Getting the current ownership of a digital asset
* const digitalAssetOwner = await aptos.getCurrentDigitalAssetOwnership({
* digitalAssetAddress: "0x123", // replace with a real digital asset address
* });
*
* console.log(digitalAssetOwner);
* }
* runExample().catch(console.error);
* ```
*/
getCurrentDigitalAssetOwnership(args: {
digitalAssetAddress: AccountAddressInput;
minimumLedgerVersion?: AnyNumber;
}): Promise<GetCurrentTokenOwnershipResponse>;
/**
* Retrieves the digital assets owned by a specified address.
*
* @param args.ownerAddress The address of the owner.
* @param args.minimumLedgerVersion Optional ledger version to sync up to before querying.
* @param args.options Optional pagination and ordering parameters for the response.
*
* @returns GetOwnedTokensResponse containing ownership data of the digital assets belonging to the ownerAddress.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Fetching the digital assets owned by the specified address
* const digitalAssets = await aptos.getOwnedDigitalAssets({
* ownerAddress: "0x1", // replace with a real account address
* });
*
* console.log(digitalAssets);
* }
* runExample().catch(console.error);
* ```
*/
getOwnedDigitalAssets(args: {
ownerAddress: AccountAddressInput;
minimumLedgerVersion?: AnyNumber;
options?: PaginationArgs & OrderByArg<GetOwnedTokensResponse[0]>;
}): Promise<GetOwnedTokensResponse>;
/**
* Retrieves the activity data for a specified digital asset using its address.
*
* @param args - The parameters for the request.
* @param args.digitalAssetAddress - The address of the digital asset.
* @param args.minimumLedgerVersion - Optional minimum ledger version to sync up to before querying.
* @param args.options - Optional pagination and ordering parameters.
*
* @returns A promise that resolves to the activity data related to the digital asset.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Get the activity data for a digital asset
* const digitalAssetActivity = await aptos.getDigitalAssetActivity({
* digitalAssetAddress: "0x123", // replace with a real digital asset address
* });
*
* console.log(digitalAssetActivity);
* }
* runExample().catch(console.error);
* ```
*/
getDigitalAssetActivity(args: {
digitalAssetAddress: AccountAddressInput;
minimumLedgerVersion?: AnyNumber;
options?: PaginationArgs & OrderByArg<GetTokenActivityResponse[0]>;
}): Promise<GetTokenActivityResponse>;
/**
* Creates a new collection within the specified account.
*
* @param args.creator - The account of the collection's creator.
* @param args.description - The description of the collection.
* @param args.name - The name of the collection.
* @param args.uri - The URI to additional info about the collection.
* @param args.options - Optional parameters for generating the transaction.
*
* The parameters below are optional:
* @param args.maxSupply - Controls the max supply of the digital assets. Defaults to MAX_U64_BIG_INT.
* @param args.mutableDescription - Controls mutability of the collection's description. Defaults to true.
* @param args.mutableRoyalty - Controls mutability of the collection's royalty. Defaults to true.
* @param args.mutableUri - Controls mutability of the collection's URI. Defaults to true.
* @param args.mutableTokenDescription - Controls mutability of the digital asset's description. Defaults to true.
* @param args.mutableTokenName - Controls mutability of the digital asset's name. Defaults to true.
* @param args.mutableTokenProperties - Controls mutability of digital asset's properties. Defaults to true.
* @param args.mutableTokenUri - Controls mutability of the digital asset's URI. Defaults to true.
* @param args.tokensBurnableByCreator - Controls whether digital assets can be burnable by the creator. Defaults to true.
* @param args.tokensFreezableByCreator - Controls whether digital assets can be frozen by the creator. Defaults to true.
* @param args.royaltyNumerator - The numerator of the royalty to be paid to the creator when a digital asset is transferred.
* Defaults to 0.
* @param args.royaltyDenominator - The denominator of the royalty to be paid to the creator when a digital asset is
* transferred. Defaults to 1.
*
* @returns A SimpleTransaction that when submitted will create the collection.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Creating a new collection transaction
* const transaction = await aptos.createCollectionTransaction({
* creator: Account.generate(), // Replace with a real account
* description: "A unique collection of digital assets.",
* name: "My Digital Collection",
* uri: "https://mycollection.com",
* });
*
* console.log("Transaction created:", transaction);
* }
* runExample().catch(console.error);
* ```
*/
createCollectionTransaction(args: {
creator: Account$1;
description: string;
name: string;
uri: string;
options?: InputGenerateTransactionOptions;
} & CreateCollectionOptions): Promise<SimpleTransaction>;
/**
* Create a transaction to mint a digital asset into the creator's account within an existing collection.
* This function helps you generate a transaction that can be simulated or submitted to the blockchain for minting a digital asset.
*
* @param args.creator - The creator of the collection.
* @param args.collection - The name of the collection the digital asset belongs to.
* @param args.description - The description of the digital asset.
* @param args.name - The name of the digital asset.
* @param args.uri - The URI to additional info about the digital asset.
* @param args.propertyKeys - Optional array of property keys for the digital asset.
* @param args.propertyTypes - Optional array of property types for the digital asset.
* @param args.propertyValues - Optional array of property values for the digital asset.
* @param args.options - Optional transaction generation options.
*
* @returns A SimpleTransaction that can be simulated or submitted to the chain.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Creating a transaction to mint a digital asset
* const transaction = await aptos.mintDigitalAssetTransaction({
* creator: Account.generate(), // replace with a real account
* collection: "MyCollection",
* description: "This is a digital asset.",
* name: "MyDigitalAsset",
* uri: "https://example.com/my-digital-asset",
* });
*
* console.log(transaction);
* }
* runExample().catch(console.error);
* ```
*/
mintDigitalAssetTransaction(args: {
creator: Account$1;
collection: string;
description: string;
name: string;
uri: string;
propertyKeys?: Array<string>;
propertyTypes?: Array<PropertyType>;
propertyValues?: Array<PropertyValue>;
options?: InputGenerateTransactionOptions;
}): Promise<SimpleTransaction>;
/**
* Transfer ownership of a non-fungible digital asset.
* This function allows you to transfer a digital asset only if it is not frozen, meaning the ownership transfer is not disabled.
*
* @param args The arguments for transferring the digital asset.
* @param args.sender The sender account of the current digital asset owner.
* @param args.digitalAssetAddress The address of the digital asset being transferred.
* @param args.recipient The account address of the recipient.
* @param args.digitalAssetType Optional. The type of the digital asset, defaults to "0x4::token::Token".
* @param args.options Optional. Additional options for generating the transaction.
*
* @returns A SimpleTransaction that can be simulated or submitted to the chain.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Transfer a digital asset
* const transaction = await aptos.transferDigitalAssetTransaction({
* sender: Account.generate(), // replace with a real sender account
* digitalAssetAddress: "0x123", // replace with a real digital asset address
* recipient: "0x456", // replace with a real recipient account address
* });
*
* console.log(transaction);
* }
* runExample().catch(console.error);
* ```
*/
transferDigitalAssetTransaction(args: {
sender: Account$1;
digitalAssetAddress: AccountAddressInput;
recipient: AccountAddress;
digitalAssetType?: MoveStructId;
options?: InputGenerateTransactionOptions;
}): Promise<SimpleTransaction>;
/**
* Mint a soul bound digital asset into a recipient's account.
* This function allows you to create a unique digital asset that is bound to a specific account.
*
* @param args - The arguments for minting the soul bound transaction.
* @param args.account - The account that mints the digital asset.
* @param args.collection - The collection name that the digital asset belongs to.
* @param args.description - The digital asset description.
* @param args.name - The digital asset name.
* @param args.uri - The digital asset URL.
* @param args.recipient - The account address where the digital asset will be created.
* @param args.propertyKeys - The property keys for storing on-chain properties.
* @param args.propertyTypes - The type of property values.
* @param args.propertyValues - The property values to be stored on-chain.
* @param args.options - Additional options for generating the transaction.
*
* @returns A SimpleTransaction that can be simulated or submitted to the chain.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Mint a soul bound digital asset
* const transaction = await aptos.mintSoulBoundTransaction({
* account: Account.generate(), // Replace with a real account
* collection: "collectionName",
* description: "collectionDescription",
* name: "digitalAssetName",
* uri: "digital-asset-uri.com",
* recipient: "0x123" // Replace with a real recipient account address
* });
*
* console.log(transaction);
* }
* runExample().catch(console.error);
* ```
*/
mintSoulBoundTransaction(args: {
account: Account$1;
collection: string;
description: string;
name: string;
uri: string;
recipient: AccountAddressInput;
propertyKeys?: Array<string>;
propertyTypes?: Array<PropertyType>;
propertyValues?: Array<PropertyValue>;
options?: InputGenerateTransactionOptions;
}): Promise<SimpleTransaction>;
/**
* Burn a digital asset by its creator, allowing for the removal of a specified digital asset from the blockchain.
*
* @param args The arguments for burning the digital asset.
* @param args.creator The creator account that is burning the digital asset.
* @param args.digitalAssetAddress The address of the digital asset to be burned.
* @param args.digitalAssetType Optional. The type of the digital asset being burned.
* @param args.options Optional. Additional options for generating the transaction.
*
* @returns A SimpleTransaction that can be simulated or submitted to the chain.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network, Account } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* const creator = Account.generate(); // Replace with a real creator account
* const transaction = await aptos.burnDigitalAssetTransaction({
* creator: creator,
* digitalAssetAddress: "0x123", // Replace with a real digital asset address
* });
*
* console.log(transaction);
* }
* runExample().catch(console.error);
* ```
*/
burnDigitalAssetTransaction(args: {
creator: Account$1;
digitalAssetAddress: AccountAddressInput;
digitalAssetType?: MoveStructId;
options?: InputGenerateTransactionOptions;
}): Promise<SimpleTransaction>;
/**
* Freeze the ability to transfer a specified digital asset.
* This function allows the creator to restrict the transfer capability of a digital asset.
*
* @param args The arguments for freezing the digital asset transfer.
* @param args.creator The creator account initiating the freeze.
* @param args.digitalAssetAddress The address of the digital asset to be frozen.
* @param args.digitalAssetType Optional. The type of the digital asset being frozen.
* @param args.options Optional. Additional options for generating the transaction.
*
* @returns A SimpleTransaction that can be simulated or submitted to the chain.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Freeze the digital asset transfer
* const transaction = await aptos.freezeDigitalAssetTransaferTransaction({
* creator: Account.generate(), // Replace with a real account if needed
* digitalAssetAddress: "0x123", // Replace with a real digital asset address
* });
*
* console.log(transaction);
* }
* runExample().catch(console.error);
* ```
*/
freezeDigitalAssetTransaferTransaction(args: {
creator: Account$1;
digitalAssetAddress: AccountAddressInput;
digitalAssetType?: MoveStructId;
options?: InputGenerateTransactionOptions;
}): Promise<SimpleTransaction>;
/**
* Unfreeze the ability to transfer a digital asset.
* This function allows the specified creator account to unfreeze the transfer of a digital asset identified by its address.
*
* @param args The parameters for unfreezing the digital asset transfer.
* @param args.creator The creator account that is unfreezing the digital asset transfer.
* @param args.digitalAssetAddress The address of the digital asset to unfreeze.
* @param args.digitalAssetType Optional. The type of the digital asset being unfrozen.
* @param args.options Optional. Additional options for generating the transaction.
*
* @returns A SimpleTransaction that can be simulated or submitted to the chain.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Unfreeze the ability to transfer a digital asset
* const transaction = await aptos.unfreezeDigitalAssetTransaferTransaction({
* creator: Account.generate(), // replace with a real creator account
* digitalAssetAddress: "0x123", // replace with a real digital asset address
* });
*
* console.log(transaction);
* }
* runExample().catch(console.error);
* ```
*/
unfreezeDigitalAssetTransaferTransaction(args: {
creator: Account$1;
digitalAssetAddress: AccountAddressInput;
digitalAssetType?: MoveStructId;
options?: InputGenerateTransactionOptions;
}): Promise<SimpleTransaction>;
/**
* Set the digital asset description to provide additional context or information about the asset.
*
* @param args The parameters for setting the digital asset description.
* @param args.creator The creator account responsible for the digital asset.
* @param args.description The digital asset description to be set.
* @param args.digitalAssetAddress The address of the digital asset.
* @param args.digitalAssetType Optional. The type of the digital asset.
* @param args.options Optional. Additional options for generating the transaction.
*
* @returns A SimpleTransaction that can be simulated or submitted to the chain.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Set the digital asset description
* const transaction = await aptos.setDigitalAssetDescriptionTransaction({
* creator: Account.generate(), // replace with a real account
* description: "This is a digital asset description.",
* digitalAssetAddress: "0x123", // replace with a real digital asset address
* });
*
* console.log(transaction);
* }
* runExample().catch(console.error);
* ```
*/
setDigitalAssetDescriptionTransaction(args: {
creator: Account$1;
description: string;
digitalAssetAddress: AccountAddressInput;
digitalAssetType?: MoveStructId;
options?: InputGenerateTransactionOptions;
}): Promise<SimpleTransaction>;
/**
* Set the digital asset name, allowing you to define a name for a specific digital asset on the blockchain.
*
* @param args The parameters for setting the digital asset name.
* @param args.creator The creator account responsible for the transaction.
* @param args.name The desired name for the digital asset.
* @param args.digitalAssetAddress The address of the digital asset.
* @param args.digitalAssetType Optional. The type of the digital asset, represented as a Move struct ID.
* @param args.options Optional. Additional options for generating the transaction.
*
* @returns A SimpleTransaction that can be simulated or submitted to the blockchain.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network, Account } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* const creator = Account.generate(); // Generate a new account for the creator
* const digitalAssetAddress = "0x123"; // replace with a real digital asset address
*
* // Set the digital asset name
* const transaction = await aptos.setDigitalAssetNameTransaction({
* creator: creator,
* name: "digitalAssetName",
* digitalAssetAddress: digitalAssetAddress,
* });
*
* console.log(transaction);
* }
* runExample().catch(console.error);
* ```
*/
setDigitalAssetNameTransaction(args: {
creator: Account$1;
name: string;
digitalAssetAddress: AccountAddressInput;
digitalAssetType?: MoveStructId;
options?: InputGenerateTransactionOptions;
}): Promise<SimpleTransaction>;
/**
* Set the URI for a digital asset, allowing you to associate a unique identifier with the asset.
*
* @param args The parameters for the transaction.
* @param args.creator The creator account initiating the transaction.
* @param args.uri The digital asset URI to be set.
* @param args.digitalAssetAddress The address of the digital asset.
* @param args.digitalAssetType Optional. The type of the digital asset.
* @param args.options Optional. Additional options for generating the transaction.
* @returns A SimpleTransaction that can be simulated or submitted to the chain.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Set the URI for a digital asset
* const transaction = await aptos.setDigitalAssetURITransaction({
* creator: Account.generate(), // Replace with a real creator account
* uri: "digital-asset-uri.com",
* digitalAssetAddress: "0x123", // Replace with a real digital asset address
* });
*
* console.log(transaction);
* }
* runExample().catch(console.error);
* ```
*/
setDigitalAssetURITransaction(args: {
creator: Account$1;
uri: string;
digitalAssetAddress: AccountAddressInput;
digitalAssetType?: MoveStructId;
options?: InputGenerateTransactionOptions;
}): Promise<SimpleTransaction>;
/**
* Add a digital asset property to the blockchain.
* This function allows you to specify a new property for a digital asset, including its key, type, and value.
*
* @param args - The arguments for adding a digital asset property.
* @param args.creator - The account that mints the digital asset.
* @param args.propertyKey - The property key for storing on-chain properties.
* @param args.propertyType - The type of property value.
* @param args.propertyValue - The property value to be stored on-chain.
* @param args.digitalAssetAddress - The digital asset address.
* @param args.digitalAssetType - (Optional) The type of the digital asset.
* @param args.options - (Optional) Options for generating the transaction.
* @returns A SimpleTransaction that can be simulated or submitted to the chain.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Add a digital asset property
* const transaction = await aptos.addDigitalAssetPropertyTransaction({
* creator: Account.generate(), // Replace with a real account
* propertyKey: "newKey",
* propertyType: "BOOLEAN",
* propertyValue: true,
* digitalAssetAddress: "0x123", // Replace with a real digital asset address
* });
*
* console.log(transaction);
* }
* runExample().catch(console.error);
* ```
*/
addDigitalAssetPropertyTransaction(args: {
creator: Account$1;
propertyKey: string;
propertyType: PropertyType;
propertyValue: PropertyValue;
digitalAssetAddress: AccountAddressInput;
digitalAssetType?: MoveStructId;
options?: InputGenerateTransactionOptions;
}): Promise<SimpleTransaction>;
/**
* Remove a digital asset property from the blockchain.
* This function allows you to delete an existing property associated with a digital asset.
*
* @param args The parameters required to remove the digital asset property.
* @param args.creator The account that mints the digital asset.
* @param args.propertyKey The property key for storing on-chain properties.
* @param args.propertyType The type of property value.
* @param args.propertyValue The property value to be stored on-chain.
* @param args.digitalAssetAddress The digital asset address.
* @param args.digitalAssetType Optional. The type of the digital asset.
* @param args.options Optional. Additional options for generating the transaction.
*
* @returns A SimpleTransaction that can be simulated or submitted to the chain.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Remove a digital asset property
* const transaction = await aptos.removeDigitalAssetPropertyTransaction({
* creator: Account.generate(), // replace with a real account
* propertyKey: "newKey",
* propertyType: "BOOLEAN",
* propertyValue: true,
* digitalAssetAddress: "0x123", // replace with a real digital asset address
* });
*
* console.log(transaction);
* }
* runExample().catch(console.error);
* ```
*/
removeDigitalAssetPropertyTransaction(args: {
creator: Account$1;
propertyKey: string;
propertyType: PropertyType;
propertyValue: PropertyValue;
digitalAssetAddress: AccountAddressInput;
digitalAssetType?: MoveStructId;
options?: InputGenerateTransactionOptions;
}): Promise<SimpleTransaction>;
/**
* Update a digital asset property on-chain.
*
* @param args The parameters for updating the digital asset property.
* @param args.creator The account that mints the digital asset.
* @param args.digitalAssetAddress The address of the digital asset.
* @param args.propertyKey The property key for storing on-chain properties.
* @param args.propertyType The type of property value.
* @param args.propertyValue The property value to be stored on-chain.
* @param args.digitalAssetType Optional. The type of the digital asset.
* @param args.options Optional. Additional options for generating the transaction.
*
* @returns A SimpleTransaction that can be simulated or submitted to the chain.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Update a digital asset property
* const transaction = await aptos.updateDigitalAssetPropertyTransaction({
* creator: Account.generate(), // replace with a real account
* propertyKey: "newKey",
* propertyType: "BOOLEAN",
* propertyValue: false,
* digitalAssetAddress: "0x123", // replace with a real digital asset address
* });
*
* console.log(transaction);
* }
* runExample().catch(console.error);
* ```
*/
updateDigitalAssetPropertyTransaction(args: {
creator: Account$1;
propertyKey: string;
propertyType: PropertyType;
propertyValue: PropertyValue;
digitalAssetAddress: AccountAddressInput;
digitalAssetType?: MoveStructId;
options?: InputGenerateTransactionOptions;
}): Promise<SimpleTransaction>;
/**
* Add a typed digital asset property to the blockchain.
* This function allows you to define and store a specific property for a digital asset, enabling better categorization and
* management of digital assets.
*
* @param args - The parameters for adding the typed property.
* @param args.creator - The account that mints the digital asset.
* @param args.propertyKey - The property key for storing on-chain properties.
* @param args.propertyType - The type of property value.
* @param args.propertyValue - The property value to be stored on-chain.
* @param args.digitalAssetAddress - The digital asset address.
* @param args.digitalAssetType - The optional type of the digital asset.
* @param args.options - Optional transaction generation options.
*
* @returns A SimpleTransaction that can be simulated or submitted to the chain.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Adding a typed digital asset property
* const transaction = await aptos.addDigitalAssetTypedPropertyTransaction({
* creator: Account.generate(), // replace with a real account
* propertyKey: "typedKey",
* propertyType: "STRING",
* propertyValue: "hello",
* digitalAssetAddress: "0x123", // replace with a real digital asset address
* });
*
* console.log(transaction);
* }
* runExample().catch(console.error);
* ```
*/
addDigitalAssetTypedPropertyTransaction(args: {
creator: Account$1;
propertyKey: string;
propertyType: PropertyType;
propertyValue: PropertyValue;
digitalAssetAddress: AccountAddressInput;
digitalAssetType?: MoveStructId;
options?: InputGenerateTransactionOptions;
}): Promise<SimpleTransaction>;
/**
* Update a typed digital asset property on-chain.
* This function allows you to modify the properties of a digital asset, enabling dynamic updates to its attributes.
*
* @param args - The arguments for updating the digital asset property.
* @param args.creator - The account that mints the digital asset.
* @param args.propertyKey - The property key for storing on-chain properties.
* @param args.propertyType - The type of property value.
* @param args.propertyValue - The property value to be stored on-chain.
* @param args.digitalAssetAddress - The digital asset address.
* @param args.digitalAssetType - (Optional) The type of the digital asset.
* @param args.options - (Optional) Additional options for generating the transaction.
*
* @returns A SimpleTransaction that can be simulated or submitted to the chain.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Update a typed digital asset property
* const transaction = await aptos.updateDigitalAssetTypedPropertyTransaction({
* creator: Account.generate(), // replace with a real account
* propertyKey: "typedKey",
* propertyType: "U8",
* propertyValue: 2,
* digitalAssetAddress: "0x123", // replace with a real digital asset address
* });
*
* console.log(transaction);
* }
* runExample().catch(console.error);
* ```
*/
updateDigitalAssetTypedPropertyTransaction(args: {
creator: Account$1;
propertyKey: string;
propertyType: PropertyType;
propertyValue: PropertyValue;
digitalAssetAddress: AccountAddressInput;
digitalAssetType?: MoveStructId;
options?: InputGenerateTransactionOptions;
}): Promise<SimpleTransaction>;
}
/**
* A class to query all `Event` Aptos related queries.
*/
declare class Event {
readonly config: AptosConfig;
/**
* Initializes a new instance of the Aptos client with the provided configuration.
*
* @param config - The configuration settings for the Aptos client.
* @param config.network - The network to connect to (e.g., Testnet, Mainnet).
* @param config.nodeUrl - The URL of the Aptos node to connect to.
* @param config.faucetUrl - The URL of the faucet to use for funding accounts.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* async function runExample() {
* // Create a new Aptos client with Testnet configuration
* const config = new AptosConfig({ network: Network.TESTNET }); // Specify your own network if needed
* const aptos = new Aptos(config);
*
* console.log("Aptos client initialized:", aptos);
* }
* runExample().catch(console.error);
* ```
*/
constructor(config: AptosConfig);
/**
* Retrieve module events based on a specified event type.
* This function allows you to query for events that are associated with a particular module event type in the Aptos blockchain.
*
* @param args - The arguments for retrieving module events.
* @param args.eventType - The event type to filter the results.
* @param args.minimumLedgerVersion - Optional ledger version to sync up to before querying.
* @param args.options - Optional pagination and ordering parameters for the event results.
*
* @returns Promise<GetEventsResponse> - A promise that resolves to the retrieved events.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Retrieve module events for a specific event type
* const events = await aptos.getModuleEventsByEventType({
* eventType: "0x1::transaction_fee::FeeStatement", // specify the event type
* minimumLedgerVersion: 1, // optional: specify minimum ledger version if needed
* });
*
* console.log(events); // log the retrieved events
* }
* runExample().catch(console.error);
* ```
*/
getModuleEventsByEventType(args: {
eventType: MoveStructId;
minimumLedgerVersion?: AnyNumber;
options?: PaginationArgs & OrderByArg<GetEventsResponse[0]>;
}): Promise<GetEventsResponse>;
/**
* Retrieve events associated with a specific account address and creation number.
*
* @param args - The parameters for retrieving account events.
* @param args.accountAddress - The account address to query events for.
* @param args.creationNumber - The event creation number to filter the events.
* @param args.minimumLedgerVersion - Optional minimum ledger version to sync up to before querying.
*
* @returns Promise<GetEventsResponse>
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Get events for the account at creation number 0
* const events = await aptos.getAccountEventsByCreationNumber({
* accountAddress: "0x1", // replace with a real account address
* creationNumber: 0,
* });
*
* console.log(events);
* }
* runExample().catch(console.error);
* ```
*/
getAccountEventsByCreationNumber(args: {
accountAddress: AccountAddressInput;
creationNumber: AnyNumber;
minimumLedgerVersion?: AnyNumber;
}): Promise<GetEventsResponse>;
/**
* Retrieve events associated with a specific account address and event type.
*
* @param args.accountAddress - The account address to query events for.
* @param args.eventType - The type of event to filter by.
* @param args.minimumLedgerVersion - Optional ledger version to sync up to before querying.
* @param args.options - Optional pagination and ordering parameters for the event query.
*
* @returns Promise<GetEventsResponse>
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Get events for a specific account and event type
* const events = await aptos.getAccountEventsByEventType({
* accountAddress: "0x1", // replace with a real account address
* eventType: "0x1::transaction_fee::FeeStatement", // replace with a real event type
* minimumLedgerVersion: 1, // optional, specify if needed
* });
*
* console.log(events);
* }
* runExample().catch(console.error);
* ```
*/
getAccountEventsByEventType(args: {
accountAddress: AccountAddressInput;
eventType: MoveStructId;
minimumLedgerVersion?: AnyNumber;
options?: PaginationArgs & OrderByArg<GetEventsResponse[0]>;
}): Promise<GetEventsResponse>;
/**
* Retrieve all events from the Aptos blockchain.
* An optional `where` clause can be provided to filter the results based on specific criteria.
*
* @param args Optional parameters for the query.
* @param args.minimumLedgerVersion Optional ledger version to sync up to before querying.
* @param args.options Optional pagination and filtering options.
* @param args.options.where Optional condition to filter events.
* @param args.options.offset Optional pagination offset.
* @param args.options.limit Optional maximum number of events to return.
* @param args.options.orderBy Optional ordering of the results.
*
* @returns GetEventsQuery response type containing the events.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Retrieve all events
* const events = await aptos.getEvents();
*
* // Retrieve events with filtering by account address
* const whereCondition = {
* account_address: { _eq: "0x123" }, // replace with a real account address
* };
* const filteredEvents = await aptos.getEvents({
* options: { where: whereCondition },
* });
*
* console.log(events);
* console.log(filteredEvents);
* }
* runExample().catch(console.error);
* ```
*/
getEvents(args?: {
minimumLedgerVersion?: AnyNumber;
options?: PaginationArgs & OrderByArg<GetEventsResponse[0]> & WhereArg<EventsBoolExp>;
}): Promise<GetEventsResponse>;
}
/**
* A class to query all `Faucet` related queries on Aptos.
*/
declare class Faucet {
readonly config: AptosConfig;
/**
* Initializes a new instance of the Aptos client with the specified configuration.
*
* @param config - The configuration settings for the Aptos client.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* async function runExample() {
* // Create a configuration for the Aptos client
* const config = new AptosConfig({ network: Network.TESTNET }); // specify your own network if needed
*
* // Initialize the Aptos client with the configuration
* const aptos = new Aptos(config);
*
* console.log("Aptos client initialized:", aptos);
* }
* runExample().catch(console.error);
* ```
*/
constructor(config: AptosConfig);
/**
* This function creates an account if it does not exist and mints the specified amount of coins into that account.
*
* @param args - The arguments for funding the account.
* @param args.accountAddress - The address of the account to fund.
* @param args.amount - The amount of tokens to fund the account with.
* @param args.options - Configuration options for waiting for the transaction.
* @returns Transaction hash of the transaction that funded the account.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Fund an account with a specified amount of tokens
* const transaction = await aptos.fundAccount({
* accountAddress: "0x1", // replace with your account address
* amount: 100,
* });
*
* console.log("Transaction hash:", transaction.hash);
* }
* runExample().catch(console.error);
* ```
*/
fundAccount(args: {
accountAddress: AccountAddressInput;
amount: number;
options?: WaitForTransactionOptions;
}): Promise<UserTransactionResponse>;
}
/**
* Determines if the provided argument is of type boolean.
* This can help in validating input types before processing them further.
*
* @param arg - The argument to check, which can be of various types.
* @returns A boolean indicating whether the argument is a boolean.
*/
declare function isBool(arg: SimpleEntryFunctionArgumentTypes): arg is boolean;
/**
* Checks if the provided argument is of type string.
*
* @param arg - The value to be checked for string type.
* @returns A boolean indicating whether the argument is a string.
*/
declare function isString(arg: any): arg is string;
/**
* Determines if the provided argument is of type number.
*
* @param arg - The argument to check, which can be of various types.
* @returns A boolean indicating whether the argument is a number.
*/
declare function isNumber(arg: SimpleEntryFunctionArgumentTypes): arg is number;
/**
* Converts a number or a string representation of a number into a number type.
* This function is useful for ensuring that the input is in a consistent numeric format,
* which can help prevent type mismatches in further processing.
*
* @param arg - The input value to be converted. This can be a number, a string representing a number, or any other type.
* @returns Returns the converted number if the input is valid; otherwise, it returns undefined.
*/
declare function convertNumber(arg: SimpleEntryFunctionArgumentTypes): number | undefined;
/**
* Determines if the provided argument is a large number, which can be a number, bigint, or string representation of a number.
*
* @param arg - The argument to check, which can be of type number, bigint, or string.
*/
declare function isLargeNumber(arg: SimpleEntryFunctionArgumentTypes): arg is number | bigint | string;
/**
* Checks if the provided argument is empty, meaning it is either null or undefined.
*
* @param arg - The argument to check for emptiness.
* @returns A boolean indicating whether the argument is empty.
*/
declare function isEmptyOption(arg: SimpleEntryFunctionArgumentTypes): arg is null | undefined;
/**
* Determines if the provided argument is a valid encoded entry function argument type.
* This function helps validate that the argument conforms to the expected types for entry function parameters.
*
* @param arg - The argument to check, which can be of type EntryFunctionArgumentTypes or SimpleEntryFunctionArgumentTypes.
*/
declare function isEncodedEntryFunctionArgument(arg: EntryFunctionArgumentTypes | SimpleEntryFunctionArgumentTypes): arg is EntryFunctionArgumentTypes;
declare function isBcsBool(arg: EntryFunctionArgumentTypes | SimpleEntryFunctionArgumentTypes): arg is Bool;
declare function isBcsAddress(arg: EntryFunctionArgumentTypes | SimpleEntryFunctionArgumentTypes): arg is AccountAddress;
declare function isBcsString(arg: EntryFunctionArgumentTypes | SimpleEntryFunctionArgumentTypes): arg is MoveString;
declare function isBcsFixedBytes(arg: EntryFunctionArgumentTypes | SimpleEntryFunctionArgumentTypes): arg is FixedBytes;
declare function isBcsU8(arg: EntryFunctionArgumentTypes | SimpleEntryFunctionArgumentTypes): arg is U8;
declare function isBcsU16(arg: EntryFunctionArgumentTypes | SimpleEntryFunctionArgumentTypes): arg is U16;
declare function isBcsU32(arg: EntryFunctionArgumentTypes | SimpleEntryFunctionArgumentTypes): arg is U32;
declare function isBcsU64(arg: EntryFunctionArgumentTypes | SimpleEntryFunctionArgumentTypes): arg is U64;
declare function isBcsU128(arg: EntryFunctionArgumentTypes | SimpleEntryFunctionArgumentTypes): arg is U128;
declare function isBcsU256(arg: EntryFunctionArgumentTypes | SimpleEntryFunctionArgumentTypes): arg is U256;
/**
* Determines if the provided argument contains script data input by checking for the presence of bytecode.
*
* @param arg - The input data to be checked, which can either be a payload with remote ABI or a standard payload.
* @param arg.bytecode - The bytecode of the script, present if the input is script data.
* @param arg.function - The function associated with the transaction, which is relevant for standard payloads.
* @param arg.args - The arguments for the function, applicable in the context of standard payloads.
*/
declare function isScriptDataInput(arg: InputGenerateTransactionPayloadDataWithRemoteABI | InputGenerateTransactionPayloadData): arg is InputScriptData;
/**
* Throws an error indicating a type mismatch for a specified argument position.
* This function helps in debugging by providing clear feedback on expected types.
*
* @param expectedType - The type that was expected for the argument.
* @param position - The position of the argument that caused the type mismatch.
*/
declare function throwTypeMismatch(expectedType: string, position: number): void;
/**
* Finds the index of the first non-signer argument in the function ABI parameters.
*
* A function is often defined with a `signer` or `&signer` arguments at the start, which are filled in
* by signatures and not by the caller. This function helps identify the position of the first argument that
* can be provided by the caller, allowing for easier handling of function parameters.
*
* @param functionAbi - The ABI of the function to analyze.
* @returns The index of the first non-signer argument, or the length of the parameters array if none are found.
*/
declare function findFirstNonSignerArg(functionAbi: MoveFunction): number;
/**
* Splits a function identifier into its constituent parts: module address, module name, and function name.
* This function helps in validating and extracting details from a function identifier string.
*
* @param functionArg - The function identifier string in the format "moduleAddress::moduleName::functionName".
* @returns An object containing the module address, module name, and function name.
* @throws Error if the function identifier does not contain exactly three parts.
*/
declare function getFunctionParts(functionArg: MoveFunctionId): {
moduleAddress: string;
moduleName: string;
functionName: string;
};
/**
* Builds a transaction payload based on the provided arguments and returns a transaction payload.
* This function uses the RemoteABI by default, but can also utilize a specified ABI.
* When we call our `generateTransactionPayload` function with the relevant type properties,
* Typescript can infer the return type based on the appropriate function overload.
* @param args - The input data for generating the transaction payload.
* @param args.function - The function to be called, specified in the format "moduleAddress::moduleName::functionName".
* @param args.functionArguments - The arguments to pass to the function.
* @param args.typeArguments - The type arguments for the function.
* @param args.aptosConfig - The configuration settings for Aptos.
* @param args.abi - The ABI to use for the transaction, if not using the RemoteABI.
*
* @returns TransactionPayload - The generated transaction payload, which can be of type TransactionPayloadScript,
* TransactionPayloadMultiSig, or TransactionPayloadEntryFunction.
*/
declare function generateTransactionPayload(args: InputScriptData): Promise<TransactionPayloadScript>;
declare function generateTransactionPayload(args: InputEntryFunctionDataWithRemoteABI): Promise<TransactionPayloadEntryFunction>;
declare function generateTransactionPayload(args: InputMultiSigDataWithRemoteABI): Promise<TransactionPayloadMultiSig>;
/**
* Generates a transaction payload using the provided ABI and function details.
* This function helps create a properly structured transaction payload for executing a specific function on a module.
*
* @param args - The input data required to generate the transaction payload.
* @param args.abi - The ABI of the function to be executed.
* @param args.function - The fully qualified name of the function in the format `moduleAddress::moduleName::functionName`.
* @param args.typeArguments - An array of type arguments that correspond to the function's type parameters.
* @param args.functionArguments - An array of arguments to be passed to the function.
* @param args.multisigAddress - (Optional) The address for a multisig transaction if applicable.
*
* @throws Error if the type argument count does not match the ABI or if the number of function arguments is incorrect.
*/
declare function generateTransactionPayloadWithABI(args: InputEntryFunctionDataWithABI): TransactionPayloadEntryFunction;
declare function generateTransactionPayloadWithABI(args: InputMultiSigDataWithABI): TransactionPayloadMultiSig;
/**
* Generates the payload for a view function call using the provided arguments.
* This function helps in preparing the necessary data to interact with a specific view function on the blockchain.
*
* @param args - The input data required to generate the view function payload.
* @param args.function - The function identifier in the format "moduleAddress::moduleName::functionName".
* @param args.aptosConfig - Configuration settings for the Aptos client.
* @param args.abi - The ABI (Application Binary Interface) of the module.
*
* @returns The generated payload for the view function call.
*/
declare function generateViewFunctionPayload(args: InputViewFunctionDataWithRemoteABI): Promise<EntryFunction>;
/**
* Generates a payload for a view function call using the provided ABI and arguments.
* This function ensures that the type arguments and function arguments are correctly formatted
* and match the expected counts as defined in the ABI.
*
* @param args - The input data for generating the view function payload.
* @param args.abi - The ABI of the function to be called.
* @param args.function - The full name of the function in the format "moduleAddress::moduleName::functionName".
* @param args.typeArguments - An array of type arguments to be used in the function call.
* @param args.functionArguments - An array of arguments to be passed to the function.
*
* @throws Error if the type argument count does not match the ABI or if the function arguments
* do not match the expected parameters defined in the ABI.
*/
declare function generateViewFunctionPayloadWithABI(args: InputViewFunctionDataWithABI): EntryFunction;
/**
* Generates a raw transaction that can be sent to the Aptos network.
*
* @param args - The arguments for generating the raw transaction.
* @param args.aptosConfig - The configuration for the Aptos network.
* @param args.sender - The transaction's sender account address as a hex input.
* @param args.payload - The transaction payload, which can be created using generateTransactionPayload().
* @param args.options - Optional parameters for transaction generation.
* @param args.feePayerAddress - The address of the fee payer for sponsored transactions.
*
* @returns RawTransaction - The generated raw transaction.
*/
declare function generateRawTransaction(args: {
aptosConfig: AptosConfig;
sender: AccountAddressInput;
payload: AnyTransactionPayloadInstance;
options?: InputGenerateTransactionOptions;
feePayerAddress?: AccountAddressInput;
}): Promise<RawTransaction>;
/**
* Generates a transaction based on the provided arguments.
* This function can create both simple and multi-agent transactions, allowing for flexible transaction handling.
*
* @param args - The input arguments for generating the transaction.
* @param args.aptosConfig - The configuration settings for Aptos.
* @param args.sender - The transaction's sender account address as a hex input.
* @param args.payload - The transaction payload, which can be created using `generateTransactionPayload()`.
* @param args.options - Optional. Transaction options object.
* @param args.secondarySignerAddresses - Optional. An array of addresses for additional signers in a multi-signature transaction.
* @param args.feePayerAddress - Optional. The address of the fee payer for sponsored transactions.
* @returns An instance of a transaction, which may include secondary signer addresses and a fee payer address.
*/
declare function buildTransaction(args: InputGenerateSingleSignerRawTransactionArgs): Promise<SimpleTransaction>;
declare function buildTransaction(args: InputGenerateMultiAgentRawTransactionArgs): Promise<MultiAgentTransaction>;
/**
* Generate a signed transaction for simulation before submitting it to the chain.
* This function helps in preparing a transaction that can be simulated, allowing users to verify its validity and expected behavior.
*
* @param args - The input data required to generate the signed transaction for simulation.
* @param args.transaction - An Aptos transaction type to sign.
* @param args.signerPublicKey - The public key of the signer.
* @param args.secondarySignersPublicKeys - Optional. The public keys of secondary signers if it is a multi-signer transaction.
* @param args.feePayerPublicKey - Optional. The public key of the fee payer in a sponsored transaction.
* @param args.options - Optional. Additional options for simulating the transaction.
*
* @returns A signed serialized transaction that can be simulated.
*/
declare function generateSignedTransactionForSimulation(args: InputSimulateTransactionData): Uint8Array;
declare function getAuthenticatorForSimulation(publicKey?: PublicKey): AccountAuthenticatorEd25519 | AccountAuthenticatorSingleKey | AccountAuthenticatorMultiKey | AccountAuthenticatorNoAccountAuthenticator;
/**
* Generate a signed transaction ready for submission to the blockchain.
* This function prepares the transaction by authenticating the sender and any additional signers based on the provided arguments.
*
* @param args - The input data required to generate the signed transaction.
* @param args.transaction - An Aptos transaction type containing the details of the transaction.
* @param args.senderAuthenticator - The account authenticator of the transaction sender.
* @param args.feePayerAuthenticator - The authenticator for the fee payer, required if the transaction has a fee payer address.
* @param args.additionalSignersAuthenticators - Optional authenticators for additional signers in a multi-signer transaction.
*
* @returns A Uint8Array representing the signed transaction in bytes.
*
* @throws Error if the feePayerAuthenticator is not provided for a fee payer transaction.
* @throws Error if additionalSignersAuthenticators are not provided for a multi-signer transaction.
*/
declare function generateSignedTransaction(args: InputSubmitTransactionData): Uint8Array;
/**
* Hashes the set of values using a SHA-3 256 hash algorithm.
* @param input - An array of UTF-8 strings or Uint8Array byte arrays to be hashed.
*/
declare function hashValues(input: (Uint8Array | string)[]): Uint8Array;
/**
* Generates a user transaction hash for the provided transaction payload, which must already have an authenticator.
* This function helps ensure the integrity and uniqueness of the transaction by producing a hash based on the signed transaction data.
*
* @param args - The input data required to submit the transaction.
* @param args.authenticator - The authenticator for the transaction.
* @param args.payload - The payload containing the transaction details.
* @param args.sender - The address of the sender initiating the transaction.
* @param args.sequenceNumber - The sequence number of the transaction for the sender.
*/
declare function generateUserTransactionHash(args: InputSubmitTransactionData): string;
/**
* Convert type arguments to only type tags, allowing for string representations of type tags.
*
* @param typeArguments - An optional array of type arguments that may include string representations.
* @returns An array of TypeTag objects derived from the provided type arguments.
*/
declare function standardizeTypeTags(typeArguments?: Array<TypeArgument>): Array<TypeTag>;
/**
* Fetches the ABI of a specified function from the on-chain module ABI. This function allows you to access the details of a
* specific function within a module.
*
* @param moduleAddress - The address of the module from which to fetch the function ABI.
* @param moduleName - The name of the module containing the function.
* @param functionName - The name of the function whose ABI is to be fetched.
* @param aptosConfig - The configuration settings for Aptos.
*/
declare function fetchFunctionAbi(moduleAddress: string, moduleName: string, functionName: string, aptosConfig: AptosConfig): Promise<MoveFunction | undefined>;
/**
* Fetches the ABI for an entry function from the specified module address.
* This function validates if the ABI corresponds to an entry function and retrieves its parameters.
*
* @param moduleAddress - The address of the module containing the entry function.
* @param moduleName - The name of the module containing the entry function.
* @param functionName - The name of the entry function to fetch the ABI for.
* @param aptosConfig - The configuration settings for Aptos.
* @returns An object containing the number of signers, type parameters, and function parameters.
* @throws Error if the ABI cannot be found or if the function is not an entry function.
*/
declare function fetchEntryFunctionAbi(moduleAddress: string, moduleName: string, functionName: string, aptosConfig: AptosConfig): Promise<EntryFunctionABI>;
/**
* Fetches the ABI for a view function from the specified module address.
* This function ensures that the ABI is valid and retrieves the type parameters, parameters, and return types for the view function.
*
* @param moduleAddress - The address of the module containing the view function.
* @param moduleName - The name of the module containing the view function.
* @param functionName - The name of the view function for which to fetch the ABI.
* @param aptosConfig - The configuration settings for Aptos.
* @returns An object containing the type parameters, parameters, and return types of the view function.
* @throws Error if the ABI cannot be found or if the function is not a view function.
*/
declare function fetchViewFunctionAbi(moduleAddress: string, moduleName: string, functionName: string, aptosConfig: AptosConfig): Promise<ViewFunctionABI>;
/**
* Converts a non-BCS encoded argument into BCS encoded, if necessary.
* This function checks the provided argument against the expected parameter type and converts it accordingly.
*
* @param functionName - The name of the function for which the argument is being converted.
* @param functionAbi - The ABI (Application Binary Interface) of the function, which defines its parameters.
* @param arg - The argument to be converted, which can be of various types.
* @param position - The index of the argument in the function's parameter list.
* @param genericTypeParams - An array of type tags for any generic type parameters.
*/
declare function convertArgument(functionName: string, functionAbi: FunctionABI, arg: EntryFunctionArgumentTypes | SimpleEntryFunctionArgumentTypes, position: number, genericTypeParams: Array<TypeTag>): EntryFunctionArgumentTypes;
/**
* Checks if the provided argument is BCS encoded and converts it if necessary, ensuring type compatibility with the ABI.
* This function helps in validating and converting arguments for entry functions based on their expected types.
*
* @param arg - The argument to check or convert, which can be either a simple or entry function argument type.
* @param param - The expected type tag for the argument.
* @param position - The position of the argument in the function call.
* @param genericTypeParams - An array of generic type parameters that may be used for conversion.
*/
declare function checkOrConvertArgument(arg: SimpleEntryFunctionArgumentTypes | EntryFunctionArgumentTypes, param: TypeTag, position: number, genericTypeParams: Array<TypeTag>): EntryFunctionArgumentTypes;
/**
* Derives the appropriate raw transaction type based on the provided transaction details.
* This function helps in identifying whether the transaction is a FeePayerRawTransaction,
* MultiAgentRawTransaction, or a standard RawTransaction.
*
* @param transaction - An object representing an Aptos transaction, which may include:
* - feePayerAddress - The address of the fee payer (optional).
* - secondarySignerAddresses - An array of secondary signer addresses (optional).
* - rawTransaction - The raw transaction data.
*
* @returns FeePayerRawTransaction | MultiAgentRawTransaction | RawTransaction
*/
declare function deriveTransactionType(transaction: AnyRawTransaction): AnyRawTransactionInstance;
/**
* Generates the 'signing message' form of a message to be signed.
* This function combines a domain separator with the byte representation of the message to create a signing message.
*
* @param bytes - The byte representation of the message to be signed and sent to the chain.
* @param domainSeparator - A domain separator that starts with 'APTOS::'.
*
* @returns The Uint8Array of the signing message.
*/
declare function generateSigningMessage(bytes: Uint8Array, domainSeparator: string): Uint8Array;
/**
* @deprecated
* Use CryptoHashable instead by having your class implement it and call hash() to get the signing message.
*
* Generates the 'signing message' form of a serializable value by serializing it and using the constructor name as the domain
* separator.
*
* @param serializable - An object that has a BCS serialized form.
*
* @returns The Uint8Array of the signing message.
*/
declare function generateSigningMessageForSerializable(serializable: Serializable): Uint8Array;
/**
* Generates the 'signing message' form of a transaction by deriving the type of transaction and applying the appropriate domain
* separator based on the presence of a fee payer or secondary signers.
*
* @param transaction - A transaction that is to be signed, which can include a fee payer address or secondary signer addresses.
*
* @returns The Uint8Array of the signing message.
*/
declare function generateSigningMessageForTransaction(transaction: AnyRawTransaction): Uint8Array;
/**
* Error types related to parsing type tags, indicating various issues encountered during the parsing process.
*/
declare enum TypeTagParserErrorType {
InvalidTypeTag = "unknown type",
UnexpectedGenericType = "unexpected generic type",
UnexpectedTypeArgumentClose = "unexpected '>'",
UnexpectedWhitespaceCharacter = "unexpected whitespace character",
UnexpectedComma = "unexpected ','",
TypeArgumentCountMismatch = "type argument count doesn't match expected amount",
MissingTypeArgumentClose = "no matching '>' for '<'",
MissingTypeArgument = "no type argument before ','",
UnexpectedPrimitiveTypeArguments = "primitive types not expected to have type arguments",
UnexpectedVectorTypeArgumentCount = "vector type expected to have exactly one type argument",
UnexpectedStructFormat = "unexpected struct format, must be of the form 0xaddress::module_name::struct_name",
InvalidModuleNameCharacter = "module name must only contain alphanumeric or '_' characters",
InvalidStructNameCharacter = "struct name must only contain alphanumeric or '_' characters",
InvalidAddress = "struct address must be valid"
}
/**
* Represents an error that occurs during the parsing of a type tag.
* This error extends the built-in Error class and provides additional context
* regarding the specific type tag that failed to parse and the reason for the failure.
*
* @param typeTagStr - The type tag string that failed to be parsed.
* @param invalidReason - The reason why the type tag string is considered invalid.
*/
declare class TypeTagParserError extends Error {
/**
* Constructs an error indicating a failure to parse a type tag.
* This error provides details about the specific type tag that could not be parsed and the reason for the failure.
*
* @param typeTagStr - The string representation of the type tag that failed to parse.
* @param invalidReason - The reason why the type tag is considered invalid.
*/
constructor(typeTagStr: string, invalidReason: TypeTagParserErrorType);
}
/**
* Parses a type string into a structured representation of type tags, accommodating various formats including generics and
* nested types.
*
* This function can help you accurately interpret type strings, which can include simple types, standalone structs, and complex
* nested generics.
* It supports multiple generics, spacing within generics, and nested generics of varying depths.
* All types are made of a few parts they're either:
* 1. A simple type e.g. u8
* 2. A standalone struct e.g. 0x1::account::Account
* 3. A nested struct e.g. 0x1::coin::Coin<0x1234::coin::MyCoin>
*
* There are a few more special cases that need to be handled, however.
* 1. Multiple generics e.g. 0x1::pair::Pair<u8, u16>
* 2. Spacing in the generics e.g. 0x1::pair::Pair< u8 , u16>
* 3. Nested generics of different depths e.g. 0x1::pair::Pair<0x1::coin::Coin<0x1234::coin::MyCoin>, u8>
* 4. Generics for types in ABIs are filled in with placeholders e.g. T1, T2, T3
* @param typeStr - The string representation of the type to be parsed.
* @param options - Optional settings for parsing behavior.
* @param options.allowGenerics - A flag indicating whether to allow generics in the parsing process.
* @returns The parsed type tag representation.
* @throws TypeTagParserError if the type string is malformed or does not conform to expected formats.
*/
declare function parseTypeTag(typeStr: string, options?: {
allowGenerics?: boolean;
}): TypeTag;
/**
* A class for querying and managing fungible asset-related operations on the Aptos blockchain.
*/
declare class FungibleAsset {
readonly config: AptosConfig;
/**
* Initializes a new instance of the Aptos class with the provided configuration.
* This allows you to interact with the Aptos blockchain using the specified network settings.
*
* @param config - The configuration settings for connecting to the Aptos network.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* async function runExample() {
* // Create a configuration for the Aptos client
* const config = new AptosConfig({ network: Network.TESTNET }); // Specify your own network if needed
*
* // Initialize the Aptos client with the configuration
* const aptos = new Aptos(config);
*
* console.log("Aptos client initialized:", aptos);
* }
* runExample().catch(console.error);
* ```
*/
constructor(config: AptosConfig);
/**
* Queries all fungible asset metadata.
*
* @param args Optional parameters for the query.
* @param args.minimumLedgerVersion Optional ledger version to sync up to before querying.
* @param args.options Optional configuration for pagination and filtering.
*
* @returns A list of fungible asset metadata.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Fetching fungible asset metadata
* const fungibleAssets = await aptos.getFungibleAssetMetadata();
* console.log(fungibleAssets);
* }
* runExample().catch(console.error);
* ```
*/
getFungibleAssetMetadata(args?: {
minimumLedgerVersion?: AnyNumber;
options?: PaginationArgs & WhereArg<FungibleAssetMetadataBoolExp>;
}): Promise<GetFungibleAssetMetadataResponse>;
/**
* Queries the fungible asset metadata for a specific asset type.
* This function helps retrieve detailed information about a fungible asset based on its type.
*
* @param args - The parameters for the query.
* @param args.assetType - The asset type of the fungible asset, e.g., "0x1::aptos_coin::AptosCoin" for Aptos Coin.
* @param args.minimumLedgerVersion - Optional ledger version to sync up to before querying.
*
* @returns A fungible asset metadata item.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Retrieve fungible asset metadata by asset type
* const fungibleAsset = await aptos.getFungibleAssetMetadataByAssetType({
* assetType: "0x1::aptos_coin::AptosCoin" // replace with your asset type
* });
*
* console.log(fungibleAsset);
* }
* runExample().catch(console.error);
* ```
*/
getFungibleAssetMetadataByAssetType(args: {
assetType: string;
minimumLedgerVersion?: AnyNumber;
}): Promise<GetFungibleAssetMetadataResponse[0]>;
/**
* Retrieves fungible asset metadata based on the creator address.
*
* This function allows you to query metadata for a specific fungible asset created by a given address.
*
* @param args - The parameters for the query.
* @param args.creatorAddress - The creator address of the fungible asset.
* @param args.minimumLedgerVersion - Optional ledger version to sync up to before querying.
*
* @returns A fungible asset metadata item.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Retrieve fungible asset metadata by creator address
* const fungibleAsset = await aptos.getFungibleAssetMetadataByCreatorAddress({
* creatorAddress: "0x123", // replace with a real creator address
* });
*
* console.log(fungibleAsset);
* }
* runExample().catch(console.error);
* ```
*/
getFungibleAssetMetadataByCreatorAddress(args: {
creatorAddress: AccountAddressInput;
minimumLedgerVersion?: AnyNumber;
}): Promise<GetFungibleAssetMetadataResponse>;
/**
* Queries all fungible asset activities and returns a list of their metadata.
*
* @param args Optional parameters for the query.
* @param args.minimumLedgerVersion Optional ledger version to sync up to, before querying.
* @param args.options Optional configuration for pagination and filtering.
* @returns A list of fungible asset metadata.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Fetching fungible asset activities
* const fungibleAssetActivities = await aptos.getFungibleAssetActivities();
* console.log(fungibleAssetActivities);
* }
* runExample().catch(console.error);
* ```
*/
getFungibleAssetActivities(args?: {
minimumLedgerVersion?: AnyNumber;
options?: PaginationArgs & WhereArg<FungibleAssetActivitiesBoolExp>;
}): Promise<GetFungibleAssetActivitiesResponse>;
/**
* Queries all fungible asset balances.
*
* @param args Optional parameters for the query.
* @param args.minimumLedgerVersion Optional ledger version to sync up to, before querying.
* @param args.options Optional configuration for pagination and filtering.
*
* @returns A list of fungible asset metadata.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Fetching current fungible asset balances
* const fungibleAssetBalances = await aptos.getCurrentFungibleAssetBalances();
*
* console.log(fungibleAssetBalances);
* }
* runExample().catch(console.error);
* ```
*/
getCurrentFungibleAssetBalances(args?: {
minimumLedgerVersion?: AnyNumber;
options?: PaginationArgs & WhereArg<CurrentFungibleAssetBalancesBoolExp>;
}): Promise<GetCurrentFungibleAssetBalancesResponse>;
/**
* Transfer a specified amount of fungible asset from the sender's primary store to the recipient's primary store.
* This method allows you to transfer any fungible asset, including fungible tokens.
*
* @param args - The arguments for the transfer operation.
* @param args.sender - The sender account.
* @param args.fungibleAssetMetadataAddress - The fungible asset account address. For example, if you’re transferring USDT,
* this would be the USDT address.
* @param args.recipient - The recipient account address.
* @param args.amount - The number of assets to transfer.
* @param args.options - Optional parameters for generating the transaction.
*
* @returns A SimpleTransaction that can be simulated or submitted to the chain.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Transfer fungible asset from sender to recipient
* const transaction = await aptos.transferFungibleAsset({
* sender: Account.generate(), // replace with a real sender account
* fungibleAssetMetadataAddress: "0x123", // replace with a real fungible asset address
* recipient: "0x456", // replace with a real recipient account
* amount: 5
* });
*
* console.log(transaction);
* }
* runExample().catch(console.error);
* ```
*/
transferFungibleAsset(args: {
sender: Account$1;
fungibleAssetMetadataAddress: AccountAddressInput;
recipient: AccountAddressInput;
amount: AnyNumber;
options?: InputGenerateTransactionOptions;
}): Promise<SimpleTransaction>;
}
/**
* A class to query various Aptos-related information and perform operations on the Aptos blockchain.
*/
declare class General {
readonly config: AptosConfig;
/**
* Initializes a new instance of the Aptos client with the specified configuration.
* This allows users to interact with the Aptos blockchain using the provided settings.
*
* @param config - The configuration settings for the Aptos client.
* @param config.network - The network to connect to (e.g., TESTNET, MAINNET).
* @param config.nodeUrl - The URL of the Aptos node to connect to.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* async function runExample() {
* // Create a configuration for the Aptos client
* const config = new AptosConfig({
* network: Network.TESTNET, // specify the network
* nodeUrl: "https://testnet.aptos.dev" // specify the node URL
* });
*
* // Initialize the Aptos client with the configuration
* const aptos = new Aptos(config);
*
* console.log("Aptos client initialized:", aptos);
* }
* runExample().catch(console.error);
* ```
*/
constructor(config: AptosConfig);
/**
* Queries for the Aptos ledger information.
*
* @returns The Aptos Ledger Info, which includes details such as chain ID, epoch, and ledger version.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Fetching the ledger information
* const ledgerInfo = await aptos.getLedgerInfo();
*
* console.log(ledgerInfo);
* }
* runExample().catch(console.error);
* ```
*/
getLedgerInfo(): Promise<LedgerInfo>;
/**
* Retrieves the chain ID of the Aptos blockchain.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Fetching the chain ID
* const chainId = await aptos.getChainId();
* console.log("Chain ID:", chainId);
* }
* runExample().catch(console.error);
*
* @returns The chain ID of the Aptos blockchain.
* ```
*/
getChainId(): Promise<number>;
/**
* Retrieves block information by the specified ledger version.
*
* @param args - The arguments for retrieving the block.
* @param args.ledgerVersion - The ledger version to lookup block information for.
* @param args.options - Optional parameters for the request.
* @param args.options.withTransactions - If set to true, include all transactions in the block.
*
* @returns Block information with optional transactions.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Retrieve block information for a specific ledger version
* const block = await aptos.getBlockByVersion({ ledgerVersion: 5 });
* console.log(block);
* }
* runExample().catch(console.error);
* ```
*/
getBlockByVersion(args: {
ledgerVersion: AnyNumber;
options?: {
withTransactions?: boolean;
};
}): Promise<Block>;
/**
* Retrieve a block by its height, allowing for the inclusion of transactions if specified.
*
* @param args - The parameters for the block retrieval.
* @param args.blockHeight - The block height to look up, starting at 0.
* @param args.options - Optional settings for the retrieval.
* @param args.options.withTransactions - If set to true, includes all transactions in the block.
*
* @returns The block with optional transactions included.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Retrieve the block at height 5, including transactions
* const block = await aptos.getBlockByHeight({ blockHeight: 5, options: { withTransactions: true } });
* console.log(block);
* }
* runExample().catch(console.error);
* ```
*/
getBlockByHeight(args: {
blockHeight: AnyNumber;
options?: {
withTransactions?: boolean;
};
}): Promise<Block>;
/**
* Queries for a Move view function
* @param args.payload Payload for the view function
* @param args.options.ledgerVersion The ledger version to query, if not provided it will get the latest version
*
* @example
* const data = await aptos.view({
* payload: {
* function: "0x1::coin::balance",
* typeArguments: ["0x1::aptos_coin::AptosCoin"],
* functionArguments: [accountAddress],
* }
* })
*
* @returns an array of Move values
*/
view<T extends Array<MoveValue>>(args: {
payload: InputViewFunctionData;
options?: LedgerVersionArg;
}): Promise<T>;
/**
* Queries for a Move view function with JSON, this provides compatability with the old `aptos` package
* @param args.payload Payload for the view function
* @param args.options.ledgerVersion The ledger version to query, if not provided it will get the latest version
*
* @example
* const data = await aptos.view({
* payload: {
* function: "0x1::coin::balance",
* typeArguments: ["0x1::aptos_coin::AptosCoin"],
* functionArguments: [accountAddress.toString()],
* }
* })
*
* @returns an array of Move values
*/
viewJson<T extends Array<MoveValue>>(args: {
payload: InputViewFunctionJsonData;
options?: LedgerVersionArg;
}): Promise<T>;
/**
* Queries the top user transactions based on the specified limit.
*
* @param args - The arguments for querying top user transactions.
* @param args.limit - The number of transactions to return.
* @returns GetChainTopUserTransactionsResponse
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Fetch the top user transactions with a limit of 5
* const topUserTransactions = await aptos.getChainTopUserTransactions({ limit: 5 });
*
* console.log(topUserTransactions);
* }
* runExample().catch(console.error);
* ```
*/
getChainTopUserTransactions(args: {
limit: number;
}): Promise<GetChainTopUserTransactionsResponse>;
/**
* Retrieves data from the Aptos Indexer using a GraphQL query.
* This function allows you to execute complex queries to fetch specific data from the Aptos blockchain.
*
* @param args.query.query - A GraphQL query string.
* @param args.query.variables - The variables for the query (optional).
*
* @return The provided T type.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Querying the Aptos Indexer for ledger information
* const topUserTransactions = await aptos.queryIndexer({
* query: `query MyQuery {
* ledger_infos {
* chain_id
* }
* }`
* });
*
* console.log(topUserTransactions);
* }
* runExample().catch(console.error);
* ```
*/
queryIndexer<T extends {}>(args: {
query: GraphqlQuery;
}): Promise<T>;
/**
* Queries for the last successful indexer version, providing insight into the ledger version the indexer is updated to, which
* may lag behind the full nodes.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Get the last successful indexer version
* const version = await aptos.getIndexerLastSuccessVersion();
* console.log(`Last successful indexer version: ${version}`);
* }
* runExample().catch(console.error);
* ```
*/
getIndexerLastSuccessVersion(): Promise<bigint>;
/**
* Query the processor status for a specific processor type.
*
* @param processorType The processor type to query.
* @returns The status of the specified processor type.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Get the processor status for the account transactions processor
* const status = await aptos.getProcessorStatus("account_transactions_processor");
* console.log(status);
* }
* runExample().catch(console.error);
* ```
*/
getProcessorStatus(processorType: ProcessorType): Promise<GetProcessorStatusResponse[0]>;
}
/**
* This file contains the underlying implementations for exposed API surface in
* the {@link api/name}. By moving the methods out into a separate file,
* other namespaces and processes can access these methods without depending on the entire
* name namespace and without having a dependency cycle error.
*/
/**
* Parameters for registering a name in the Aptos network.
*
* @param aptosConfig - Configuration settings for the Aptos network.
* @param sender - The account initiating the name registration.
* @param name - The name to be registered.
* @param expiration - The expiration policy for the name registration.
*/
interface RegisterNameParameters {
aptosConfig: AptosConfig;
sender: Account$1;
name: string;
expiration: {
policy: "domain";
years?: 1;
} | {
policy: "subdomain:follow-domain";
} | {
policy: "subdomain:independent";
expirationDate: number;
};
transferable?: boolean;
toAddress?: AccountAddressInput;
targetAddress?: AccountAddressInput;
options?: InputGenerateTransactionOptions;
}
/**
* Options for querying names, including pagination, ordering, and filtering criteria.
*
* @param options - Pagination and filtering options for the query.
*/
interface QueryNamesOptions {
options?: PaginationArgs & OrderByArg<GetANSNameResponse[0]> & WhereArg<CurrentAptosNamesBoolExp>;
}
/**
* Arguments for retrieving account names based on the specified account address.
*
* @param accountAddress - The address of the account for which names are to be retrieved.
*/
interface GetAccountNamesArgs extends QueryNamesOptions {
accountAddress: AccountAddressInput;
}
/**
* Arguments for retrieving the domains associated with a specific account.
*
* @param accountAddress - The address of the account for which to fetch domains.
*/
interface GetAccountDomainsArgs extends QueryNamesOptions {
accountAddress: AccountAddressInput;
}
/**
* Arguments for retrieving subdomains associated with a specific account.
*
* @param accountAddress - The address of the account for which to fetch subdomains.
*/
interface GetAccountSubdomainsArgs extends QueryNamesOptions {
accountAddress: AccountAddressInput;
}
/**
* Arguments for retrieving subdomains associated with a specific domain.
*
* @param domain - The domain for which to fetch subdomains.
*/
interface GetDomainSubdomainsArgs extends QueryNamesOptions {
domain: string;
}
/**
* A class to handle all `ANS` operations.
*/
declare class ANS {
readonly config: AptosConfig;
/**
* Initializes a new instance of the Aptos class with the provided configuration.
* This allows you to interact with the Aptos blockchain using the specified network settings.
*
* @param config - The configuration settings for the Aptos client.
* @param config.network - The network to connect to (e.g., mainnet, testnet).
* @param config.nodeUrl - The URL of the Aptos node to connect to.
* @param config.faucetUrl - The URL of the faucet to use for funding accounts.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* async function runExample() {
* // Create a configuration for connecting to the Aptos testnet
* const config = new AptosConfig({ network: Network.TESTNET });
*
* // Initialize the Aptos client with the configuration
* const aptos = new Aptos(config);
*
* console.log("Aptos client initialized:", aptos);
* }
* runExample().catch(console.error);
* ```
*/
constructor(config: AptosConfig);
/**
* Retrieve the owner address of a specified domain name or subdomain name from the contract.
*
* @param args - The arguments for retrieving the owner address.
* @param args.name - A string representing the name of the domain or subdomain to retrieve the owner address for.
*
* @returns AccountAddress if the name is owned, undefined otherwise.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Retrieve the owner address of "test.aptos"
* const owner = await aptos.getOwnerAddress({ name: "test.aptos" });
* console.log(owner); // Logs the owner address or undefined if not owned
* }
* runExample().catch(console.error);
* ```
*/
getOwnerAddress(args: {
name: string;
}): Promise<AccountAddress | undefined>;
/**
* Retrieve the expiration time of a domain name or subdomain name from the contract.
*
* @param args - The arguments for retrieving the expiration.
* @param args.name - A string of the name to retrieve.
*
* @returns number as a unix timestamp in milliseconds.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Get the expiration time for the domain "test.aptos"
* const exp = await aptos.getExpiration({ name: "test.aptos" });
*
* // Log the expiration date
* console.log(new Date(exp)); // Outputs the expiration date
* }
* runExample().catch(console.error);
* ```
*/
getExpiration(args: {
name: string;
}): Promise<number | undefined>;
/**
* Retrieve the target address of a domain or subdomain name, which indicates the address the name points to for use on-chain.
* Note that the target address can point to addresses that do not own the name.
*
* @param args - The arguments for retrieving the target address.
* @param args.name - A string representing the name, which can be a primary name, a subdomain, or a combination (e.g.,
* "primary", "primary.apt", "secondary.primary", "secondary.primary.apt").
*
* @returns AccountAddress if the name has a target, undefined otherwise.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Retrieve the target address for the specified domain name
* const targetAddr = await aptos.getTargetAddress({ name: "test.aptos" });
*
* console.log(targetAddr); // Logs the target address, e.g., 0x123...
* }
* runExample().catch(console.error);
* ```
*/
getTargetAddress(args: {
name: string;
}): Promise<AccountAddress | undefined>;
/**
* Sets the target address of a domain or subdomain name, pointing it to a specified address for use on-chain.
* The target address can be different from the owner of the name.
*
* @param args - The arguments for setting the target address.
* @param args.sender - The account initiating the transaction.
* @param args.name - A string representing the domain or subdomain name (e.g., "test.aptos").
* @param args.address - The AccountAddressInput of the address to set the domain or subdomain to.
* @param args.options - Optional settings for generating the transaction.
*
* @returns SimpleTransaction
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Setting the target address for a domain name
* const sender = Account.generate(); // replace with a real account
* const address = "0x1"; // replace with a real account address
*
* await aptos.setTargetAddress({
* sender: sender,
* name: "test.aptos",
* address: address,
* });
*
* const targetAddress = await aptos.getTargetAddress({ name: "test.aptos" });
* console.log(targetAddress); // Should log the address set for "test.aptos"
* }
* runExample().catch(console.error);
* ```
*/
setTargetAddress(args: {
sender: Account$1;
name: string;
address: AccountAddressInput;
options?: InputGenerateTransactionOptions;
}): Promise<SimpleTransaction>;
/**
* Retrieve the primary name for an account. An account can have multiple names, but only one primary name, which may not exist.
*
* @param args - The arguments for retrieving the primary name.
* @param args.address - An AccountAddressInput (address) of the account.
*
* @returns A string if the account has a primary name, undefined otherwise.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Retrieve the primary name for the specified account address
* const name = await aptos.getPrimaryName({ address: "0x1" }); // replace with a real account address
* console.log(name);
* }
* runExample().catch(console.error);
* ```
*/
getPrimaryName(args: {
address: AccountAddressInput;
}): Promise<string | undefined>;
/**
* Sets the primary name for the sender account, allowing them to designate a single primary name among potentially multiple
* names. An account may not have a primary name.
*
* @param args - The arguments for setting the primary name.
* @param args.sender - The sender account.
* @param args.name - A string representing the name to set as primary (e.g., "test.aptos").
* @param args.options - Optional transaction options.
*
* @returns SimpleTransaction
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Set the primary name for the sender account
* const sender = Account.generate(); // replace with a real account
* await aptos.setPrimaryName({ sender, name: "test.aptos" });
*
* const primaryName = await aptos.getPrimaryName({ address: sender.accountAddress });
* console.log("Primary Name:", primaryName); // Should log: "Primary Name: test.aptos"
* }
* runExample().catch(console.error);
* ```
*/
setPrimaryName(args: {
sender: Account$1;
name?: string;
options?: InputGenerateTransactionOptions;
}): Promise<SimpleTransaction>;
/**
* Registers a new name.
*
* This function allows you to register a domain or subdomain name with specific expiration policies and options.
*
* @param args.sender - The sender account.
* @param args.name - A string of the name to register. This can be inclusive or exclusive of the .apt suffix. Examples include:
* "test", "test.apt", "test.aptos.apt", etc.
* @param args.expiration - An object with the expiration policy of the name.
* @param args.expiration.policy - 'domain' | 'subdomain:follow-domain' | 'subdomain:independent'.
* - domain: Years is required and the name will expire after the given number of years.
* - subdomain:follow-domain: The name will expire at the same time as the domain name.
* - subdomain:independent: The name will expire at the given date.
* @param args.expiration.expirationDate - An epoch number in milliseconds of the date when the subdomain will expire. Only
* applicable when the policy is set to 'subdomain:independent'.
* @param args.transferable - Determines if the subdomain being minted is soul-bound. Applicable only to subdomains.
* @param args.targetAddress optional - The address the domain name will resolve to. If not provided, the sender's address will
* be used.
* @param args.toAddress optional - The address to send the domain name to. If not provided, the transaction will be sent to the
* router.
*
* @returns SimpleTransaction
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Registering a subdomain name assuming def.apt is already registered and belongs to the sender alice.
* const txn = await aptos.registerName({
* sender: "0x1", // replace with a real sender account
* name: "test.aptos.apt",
* expiration: {
* policy: "subdomain:independent",
* expirationDate: Date.now() + 30 * 24 * 60 * 60 * 1000, // expires in 30 days
* },
* });
*
* console.log("Transaction:", txn);
* }
* runExample().catch(console.error);
* ```
*/
registerName(args: Omit<RegisterNameParameters, "aptosConfig">): Promise<SimpleTransaction>;
/**
* Renews a domain name for one year.
* If a domain name was minted with V1 of the contract, it will automatically be upgraded to V2 via this transaction.
*
* @param args - The arguments for renewing the domain.
* @param args.sender - The sender account, which must be the domain owner.
* @param args.name - A string representing the domain to renew. Subdomains cannot be renewed.
* @param args.years - The number of years to renew the name. Currently, only one year is permitted.
* @param args.options - Optional transaction options.
*
* @returns SimpleTransaction
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Renew the domain "test" for one year
* const transaction = await aptos.renewDomain({
* sender: Account.generate(), // replace with a real account
* name: "test"
* });
*
* console.log(transaction);
* }
* runExample().catch(console.error);
* ```
*/
renewDomain(args: {
sender: Account$1;
name: string;
years?: 1;
options?: InputGenerateTransactionOptions;
}): Promise<SimpleTransaction>;
/**
* Fetches a single name from the indexer based on the provided name argument.
*
* @param args - The arguments for retrieving the name.
* @param args.name - A string of the name to retrieve, e.g. "test.aptos.apt" or "test.apt" or "test".
* Can be inclusive or exclusive of the .apt suffix and can be a subdomain.
*
* @returns A promise of an ANSName or undefined if the name is not active.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Fetching a name from the indexer
* const name = await aptos.getName({ name: "test.aptos" }); // replace with a real name
* console.log(name);
* }
* runExample().catch(console.error);
* ```
*/
getName(args: {
name: string;
}): Promise<GetANSNameResponse[0] | undefined>;
/**
* Fetches all names for an account, including both top-level domains and subdomains.
*
* @param args - The arguments for fetching account names.
* @param args.accountAddress - An AccountAddressInput of the address to retrieve names for.
* @param args.options - Optional parameters for fetching names.
* @param args.options.offset - Optional, the offset to start from when fetching names.
* @param args.options.limit - Optional, a number of the names to fetch per request.
* @param args.options.orderBy - The order to sort the names by.
* @param args.options.where - Additional filters to apply to the query.
*
* @returns A promise of an array of ANSName.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Fetch account names for a specific address
* const accountNames = await aptos.getAccountNames({
* accountAddress: "0x1", // replace with a real account address
* options: {
* limit: 10, // specify how many names to fetch
* orderBy: "name", // specify the order by which to sort the names
* },
* });
*
* console.log(accountNames);
* }
* runExample().catch(console.error);
* ```
*/
getAccountNames(args: GetAccountNamesArgs): Promise<GetANSNameResponse>;
/**
* Fetches all top-level domain names for a specified account.
*
* @param args - The arguments for retrieving account domains.
* @param args.accountAddress - An AccountAddressInput of the address to retrieve domain names for.
* @param args.options.offset - Optional, the offset to start from when fetching names.
* @param args.options.limit - Optional, a number of the names to fetch per request.
* @param args.options.orderBy - The order to sort the names by.
* @param args.options.where - Additional filters to apply to the query.
*
* @returns A promise of an array of ANSName.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Fetching all top-level domain names for a specific account
* const domains = await aptos.getAccountDomains({
* accountAddress: "0x1", // replace with a real account address
* options: {
* limit: 10, // specify the number of names to fetch
* offset: 0, // specify the offset for pagination
* orderBy: "created_at", // specify the order by which to sort the names
* where: {
* // additional filters can be specified here
* },
* },
* });
*
* console.log(domains);
* }
* runExample().catch(console.error);
* ```
*/
getAccountDomains(args: GetAccountDomainsArgs): Promise<GetANSNameResponse>;
/**
* Fetches all subdomain names for a specified account.
*
* @param args - The arguments for retrieving subdomains.
* @param args.accountAddress - The address to retrieve subdomain names for.
* @param args.options - Optional parameters for fetching subdomains.
* @param args.options.offset - The offset to start from when fetching names.
* @param args.options.limit - The number of names to fetch per request.
* @param args.options.orderBy - The order to sort the names by.
* @param args.options.where - Additional filters to apply to the query.
*
* @returns A promise of an array of ANSName.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Fetching subdomain names for a specific account
* const subdomains = await aptos.getAccountSubdomains({
* accountAddress: "0x1", // replace with a real account address
* options: {
* limit: 10, // specify the number of subdomains to fetch
* offset: 0, // specify the offset for pagination
* orderBy: "name", // specify the order by which to sort the names
* },
* });
*
* console.log(subdomains);
* }
* runExample().catch(console.error);
* ```
*/
getAccountSubdomains(args: GetAccountSubdomainsArgs): Promise<GetANSNameResponse>;
/**
* Fetches all subdomain names for a given domain, excluding the domain itself.
*
* @param args - The arguments for fetching subdomains.
* @param args.domain - A string of the domain name, e.g., "test.apt" or "test" (without the suffix of .apt).
* @param args.options - Optional parameters for fetching subdomains.
* @param args.options.offset - Optional, the offset to start from when fetching names.
* @param args.options.limit - Optional, the number of names to fetch per request.
* @param args.options.orderBy - The order to sort the names by.
* @param args.options.where - Additional filters to apply to the query.
*
* @returns A promise that resolves to an array of ANSName.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Fetching subdomains for a specific domain
* const subdomains = await aptos.getDomainSubdomains({
* domain: "test", // replace with your domain
* options: {
* limit: 10, // specify the number of subdomains to fetch
* offset: 0, // specify the starting point for fetching
* orderBy: "name", // specify the order by which to sort the results
* },
* });
*
* console.log(subdomains);
* }
* runExample().catch(console.error);
* ```
*/
getDomainSubdomains(args: GetDomainSubdomainsArgs): Promise<GetANSNameResponse>;
}
/**
* A class to query all `Staking` related queries on Aptos.
*/
declare class Staking {
readonly config: AptosConfig;
/**
* Creates an instance of the Aptos client with the specified configuration.
* This allows you to interact with the Aptos blockchain using the provided settings.
*
* @param config - The configuration settings for the Aptos client.
* @param config.network - The network to connect to (e.g., TESTNET, MAINNET).
* @param config.nodeUrl - The URL of the Aptos node to connect to.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* async function runExample() {
* // Create a configuration for the Aptos client
* const config = new AptosConfig({ network: Network.TESTNET }); // Specify your network
*
* // Initialize the Aptos client with the configuration
* const aptos = new Aptos(config);
*
* console.log("Aptos client initialized:", aptos);
* }
* runExample().catch(console.error);
* ```
*/
constructor(config: AptosConfig);
/**
* Queries the current number of delegators in a specified pool. Throws an error if the pool is not found.
*
* @param args - The parameters for the query.
* @param args.poolAddress - The address of the pool to query.
* @param args.minimumLedgerVersion - Optional ledger version to sync up to before querying.
* @returns The number of delegators for the given pool.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Get the number of delegators for a specific pool
* const delegators = await aptos.getNumberOfDelegators({ poolAddress: "0x1" }); // replace with a real pool address
* console.log(`Number of delegators: ${delegators}`);
* }
* runExample().catch(console.error);
* ```
*/
getNumberOfDelegators(args: {
poolAddress: AccountAddressInput;
minimumLedgerVersion?: AnyNumber;
}): Promise<number>;
/**
* Retrieves the current number of delegators across all pools.
*
* @param args Optional parameters for the query.
* @param args.minimumLedgerVersion Optional ledger version to sync up to before querying.
* @param args.options Optional ordering options for the response.
* @returns GetNumberOfDelegatorsForAllPoolsResponse response type containing the number of delegators per pool.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Retrieve the number of delegators for all pools
* const delegators = await aptos.getNumberOfDelegatorsForAllPools();
* console.log(delegators);
* }
* runExample().catch(console.error);
* ```
*/
getNumberOfDelegatorsForAllPools(args?: {
minimumLedgerVersion?: AnyNumber;
options?: OrderByArg<GetNumberOfDelegatorsResponse[0]>;
}): Promise<GetNumberOfDelegatorsResponse>;
/**
* Queries delegated staking activities for a specific delegator and pool.
*
* @param args - The arguments for querying delegated staking activities.
* @param args.delegatorAddress - The address of the delegator.
* @param args.poolAddress - The address of the staking pool.
* @param args.minimumLedgerVersion - Optional ledger version to sync up to before querying.
* @returns The response containing delegated staking activities.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Get delegated staking activities for a specific delegator and pool
* const activities = await aptos.getDelegatedStakingActivities({
* delegatorAddress: "0x1", // replace with a real delegator address
* poolAddress: "0x2", // replace with a real pool address
* minimumLedgerVersion: 1, // specify your own if needed
* });
*
* console.log(activities);
* }
* runExample().catch(console.error);
* ```
*/
getDelegatedStakingActivities(args: {
delegatorAddress: AccountAddressInput;
poolAddress: AccountAddressInput;
minimumLedgerVersion?: AnyNumber;
}): Promise<GetDelegatedStakingActivitiesResponse>;
}
/**
* This file contains the underlying implementations for exposed submission API surface in
* the {@link api/transaction}. By moving the methods out into a separate file,
* other namespaces and processes can access these methods without depending on the entire
* transaction namespace and without having a dependency cycle error.
*/
type FeePayerOrFeePayerAuthenticatorOrNeither = {
feePayer: Account$1;
feePayerAuthenticator?: never;
} | {
feePayer?: never;
feePayerAuthenticator: AccountAuthenticator;
} | {
feePayer?: never;
feePayerAuthenticator?: never;
};
/**
* A class to handle all `Build` transaction operations.
*/
declare class Build {
readonly config: AptosConfig;
/**
* Initializes a new instance of the Aptos client with the specified configuration.
* This allows you to interact with the Aptos blockchain using the provided settings.
*
* @param config - The configuration settings for the Aptos client.
* @param config.network - The network to connect to (e.g., TESTNET, MAINNET).
* @param config.nodeUrl - The URL of the Aptos node to connect to.
* @param config.account - The account details for authentication.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* async function runExample() {
* // Create a configuration for the Aptos client
* const config = new AptosConfig({
* network: Network.TESTNET, // specify the network
* nodeUrl: "https://testnet.aptos.dev", // specify the node URL
* });
*
* // Initialize the Aptos client
* const aptos = new Aptos(config);
*
* console.log("Aptos client initialized:", aptos);
* }
* runExample().catch(console.error);
* ```
*/
constructor(config: AptosConfig);
/**
* Build a simple transaction.
*
* This function allows you to create a transaction with specified sender and data.
*
* @param args.sender - The sender account address.
* @param args.data - The transaction data.
* @param args.options - Optional transaction configurations.
* @param args.withFeePayer - Whether there is a fee payer for the transaction.
*
* @returns SimpleTransaction
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Build a simple transaction
* const transaction = await aptos.transaction.simple({
* sender: "0x1", // replace with a real sender account address
* data: {
* function: "0x1::aptos_account::transfer",
* functionArguments: ["0x2", 100], // replace with a real destination account address
* },
* options: {
* gasUnitPrice: 100, // specify your own gas unit price if needed
* maxGasAmount: 1000, // specify your own max gas amount if needed
* },
* });
*
* console.log(transaction);
* }
* runExample().catch(console.error);
* ```
*/
simple(args: {
sender: AccountAddressInput;
data: InputGenerateTransactionPayloadData;
options?: InputGenerateTransactionOptions;
withFeePayer?: boolean;
}): Promise<SimpleTransaction>;
/**
* Build a multi-agent transaction that allows multiple signers to authorize a transaction.
*
* @param args - The parameters for creating the multi-agent transaction.
* @param args.sender - The sender account address.
* @param args.data - The transaction data.
* @param args.secondarySignerAddresses - An array of the secondary signers' account addresses.
* @param args.options - Optional transaction configurations.
* @param args.withFeePayer - Whether there is a fee payer for the transaction.
*
* @returns MultiAgentTransaction
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Build a multi-agent transaction
* const transaction = await aptos.multiAgent({
* sender: "0x1", // replace with a real sender account address
* data: {
* // Transaction data structure
* function: "0x1::aptos_account::transfer",
* functionArguments: ["0x2", 100], // replace with a real destination account address and amount
* },
* secondarySignerAddresses: ["0x3", "0x4"], // replace with real secondary signer addresses
* options: {
* // Optional transaction configurations
* maxGasAmount: "1000",
* gasUnitPrice: "1",
* },
* });
*
* console.log(transaction);
* }
* runExample().catch(console.error);
* ```
*/
multiAgent(args: {
sender: AccountAddressInput;
data: InputGenerateTransactionPayloadData;
secondarySignerAddresses: AccountAddressInput[];
options?: InputGenerateTransactionOptions;
withFeePayer?: boolean;
}): Promise<MultiAgentTransaction>;
}
/**
* A class to handle all `Simulate` transaction operations.
*/
declare class Simulate {
readonly config: AptosConfig;
/**
* Initializes a new instance of the Aptos client with the specified configuration.
* This allows you to interact with the Aptos blockchain using the provided settings.
*
* @param config - The configuration settings for the Aptos client.
* @param config.network - The network to connect to (e.g., TESTNET, MAINNET).
* @param config.nodeUrl - The URL of the Aptos node to connect to.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* async function runExample() {
* // Create a configuration for the Aptos client
* const config = new AptosConfig({ network: Network.TESTNET }); // Specify your desired network
*
* // Initialize the Aptos client with the configuration
* const aptos = new Aptos(config);
*
* console.log("Aptos client initialized:", aptos);
* }
* runExample().catch(console.error);
* ```
*/
constructor(config: AptosConfig);
/**
* Simulates a transaction based on the provided parameters and returns the result.
* This function helps you understand the outcome of a transaction before executing it on the blockchain.
*
* @param args - The parameters for simulating the transaction.
* @param args.signerPublicKey - The public key of the signer for the transaction (optional).
* @param args.transaction - The raw transaction data to simulate.
* @param args.feePayerPublicKey - The public key of the fee payer (optional).
* @param args.options - Additional options for simulating the transaction (optional).
*
* @example
* ```typescript
* import {
* Account,
* Aptos,
* AptosConfig,
* Network,
* } from "@aptos-labs/ts-sdk";
*
* async function example() {
* let sender = Account.generate();
* let receiver = Account.generate();
*
* // 0. Set up the client and test accounts
* const config = new AptosConfig({ network: Network.DEVNET });
* const aptos = new Aptos(config);
*
* await aptos.fundAccount({
* accountAddress: sender.accountAddress,
* amount: 100_000_000,
* });
*
* // 1. Build the transaction to preview the impact of it
* const transaction = await aptos.transaction.build.simple({
* sender: sender.accountAddress,
* data: {
* // All transactions on Aptos are implemented via smart contracts.
* function: "0x1::aptos_account::transfer",
* functionArguments: [receiver.accountAddress, 100],
* },
* });
*
* // 2. Simulate to see what would happen if we execute this transaction
* const [userTransactionResponse] = await aptos.transaction.simulate.simple({
* signerPublicKey: sender.publicKey,
* transaction,
* });
* console.log(userTransactionResponse);
*
* // If the fee looks ok, continue to signing!
* // ...
* }
*
* example();
* ```
*/
simple(args: {
signerPublicKey?: PublicKey;
transaction: AnyRawTransaction;
feePayerPublicKey?: PublicKey;
options?: InputSimulateTransactionOptions;
}): Promise<Array<UserTransactionResponse>>;
/**
* Simulates a multi-agent transaction by generating a signed transaction and posting it to the Aptos full node.
* This function helps in understanding the outcome of a transaction involving multiple signers before it is executed.
*
* @param args - The parameters for simulating the transaction.
* @param args.signerPublicKey - The public key of the primary signer (optional).
* @param args.transaction - The raw transaction to be simulated.
* @param args.secondarySignersPublicKeys - An array of public keys for secondary signers (optional).
* Each element of the array can be optional, allowing the corresponding key check to be skipped.
* @param args.feePayerPublicKey - The public key of the fee payer (optional).
* @param args.options - Options for simulating the transaction (optional).
*
* @example
* ```typescript
* import {
* Account,
* Aptos,
* AptosConfig,
* Network,
* } from "@aptos-labs/ts-sdk";
*
* async function example() {
* let sender1 = Account.generate();
* let sender2 = Account.generate();
* let receiver = Account.generate();
*
* // 0. Set up the client and test accounts
* const config = new AptosConfig({ network: Network.DEVNET });
* const aptos = new Aptos(config);
*
* await aptos.fundAccount({
* accountAddress: sender.accountAddress,
* amount: 100_000_000,
* });
*
* // 1. Build
* console.log("\n=== 1. Building the transaction ===\n");
* const transaction = await aptos.transaction.build.multiAgent({
* sender: sender1.accountAddress,
* secondarySignerAddresses: [sender2.accountAddress],
* data: {
* // REPLACE WITH YOUR MULTI-AGENT FUNCTION HERE
* function:
* "<REPLACE WITH YOUR MULTI AGENT MOVE ENTRY FUNCTION> (Syntax {address}::{module}::{function})",
* functionArguments: [],
* },
* });
* console.log("Transaction:", transaction);
*
* // 2. Simulate (Optional)
* console.log("\n === 2. Simulating Response (Optional) === \n");
* const [userTransactionResponse] = await aptos.transaction.simulate.multiAgent(
* {
* signerPublicKey: sender1.publicKey,
* secondarySignersPublicKeys: [sender2.publicKey],
* transaction,
* },
* );
* console.log(userTransactionResponse);
*
* // If the fee looks ok, continue to signing!
* // ...
* }
*
* example();
* ```
*/
multiAgent(args: {
signerPublicKey?: PublicKey;
transaction: AnyRawTransaction;
secondarySignersPublicKeys?: Array<PublicKey | undefined>;
feePayerPublicKey?: PublicKey;
options?: InputSimulateTransactionOptions;
}): Promise<Array<UserTransactionResponse>>;
}
/**
* A class to handle all `Submit` transaction operations.
*/
declare class Submit {
readonly config: AptosConfig;
/**
* Initializes a new instance of the Aptos client with the specified configuration.
* This allows you to interact with the Aptos blockchain using the provided settings.
*
* @param config - The configuration settings for the Aptos client.
* @param config.network - The network to connect to (e.g., TESTNET, MAINNET).
* @param config.nodeUrl - The URL of the Aptos node to connect to.
* @param config.faucetUrl - The URL of the faucet for obtaining test tokens.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* async function runExample() {
* // Create a configuration for the Aptos client
* const config = new AptosConfig({
* network: Network.TESTNET, // Use the TESTNET for testing
* nodeUrl: "https://testnet.aptos.dev", // Specify the node URL
* faucetUrl: "https://faucet.testnet.aptos.dev" // Specify the faucet URL
* });
*
* // Initialize the Aptos client with the configuration
* const aptos = new Aptos(config);
*
* console.log("Aptos client initialized:", aptos);
* }
* runExample().catch(console.error);
* ```
*/
constructor(config: AptosConfig);
/**
* Submits a transaction to the Aptos blockchain using the provided transaction details and authenticators.
* This function allows you to execute transactions securely by specifying the sender and optional fee payer authenticators.
*
* @param args - The arguments for submitting the transaction.
* @param args.transaction - The raw transaction data to be submitted.
* @param args.senderAuthenticator - The authenticator for the sender's account.
* @param [args.feePayerAuthenticator] - The optional authenticator for the fee payer's account.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network, Account } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* const sender = Account.generate(); // Generate a new sender account
* const transaction = await aptos.transaction.build.simple({
* sender: sender.accountAddress,
* data: {
* function: "0x1::aptos_account::transfer",
* functionArguments: [Account.generate().accountAddress, 100], // Replace with a real destination account
* },
* });
*
* // Submit the transaction
* const response = await aptos.simple({
* transaction,
* senderAuthenticator: sender.getAuthenticator(), // Use the sender's authenticator
* });
*
* console.log("Transaction submitted:", response);
* }
* runExample().catch(console.error);
* ```
*/
simple(args: {
transaction: AnyRawTransaction;
senderAuthenticator: AccountAuthenticator;
feePayerAuthenticator?: AccountAuthenticator;
}): Promise<PendingTransactionResponse>;
/**
* Submits a multi-agent transaction to the Aptos network, allowing multiple signers to authorize the transaction.
* This function is useful for scenarios where a transaction requires approval from multiple accounts.
*
* @param args - The parameters for the multi-agent transaction.
* @param args.transaction - The raw transaction to be submitted.
* @param args.senderAuthenticator - The authenticator for the sender account.
* @param args.additionalSignersAuthenticators - An array of authenticators for additional signers.
* @param [args.feePayerAuthenticator] - An optional authenticator for the fee payer account.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network, Account } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* const sender = Account.generate(); // Generate a new sender account
* const additionalSigner1 = Account.generate(); // Generate an additional signer account
* const additionalSigner2 = Account.generate(); // Generate another additional signer account
*
* const transaction = await aptos.transaction.build.simple({
* sender: sender.accountAddress,
* data: {
* function: "0x1::aptos_account::transfer",
* functionArguments: [additionalSigner1.accountAddress, 100],
* },
* });
*
* const response = await aptos.multiAgent({
* transaction,
* senderAuthenticator: sender.getAuthenticator(), // Use the sender's authenticator
* additionalSignersAuthenticators: [
* additionalSigner1.getAuthenticator(), // Use the first additional signer's authenticator
* additionalSigner2.getAuthenticator(), // Use the second additional signer's authenticator
* ],
* });
*
* console.log(response); // Log the response from the transaction submission
* }
* runExample().catch(console.error);
* ```
*/
multiAgent(args: {
transaction: AnyRawTransaction;
senderAuthenticator: AccountAuthenticator;
additionalSignersAuthenticators: Array<AccountAuthenticator>;
feePayerAuthenticator?: AccountAuthenticator;
}): Promise<PendingTransactionResponse>;
}
/**
* A wrapper that handles and manages an account sequence number.
*
* Submit up to `maximumInFlight` transactions per account in parallel with a timeout of `sleepTime`
* If local assumes `maximumInFlight` are in flight, determine the actual committed state from the network
* If there are less than `maximumInFlight` due to some being committed, adjust the window
* If `maximumInFlight` are in flight, wait `sleepTime` seconds before re-evaluating
* If ever waiting more than `maxWaitTime` restart the sequence number to the current on-chain state
*
* Assumptions:
* Accounts are expected to be managed by a single AccountSequenceNumber and not used otherwise.
* They are initialized to the current on-chain state, so if there are already transactions in
* flight, they may take some time to reset.
* Accounts are automatically initialized if not explicitly
*
* Notes:
* This is co-routine safe, that is many async tasks can be reading from this concurrently.
* The state of an account cannot be used across multiple AccountSequenceNumber services.
* The synchronize method will create a barrier that prevents additional nextSequenceNumber
* calls until it is complete.
* This only manages the distribution of sequence numbers it does not help handle transaction
* failures.
* If a transaction fails, you should call synchronize and wait for timeouts.
*/
/**
* Represents an account's sequence number management for transaction handling on the Aptos blockchain.
* This class provides methods to retrieve the next available sequence number, synchronize with the on-chain sequence number,
* and manage local sequence numbers while ensuring thread safety.
*
* @param aptosConfig - The configuration settings for Aptos.
* @param account - The account associated with the sequence number.
* @param maxWaitTime - The maximum time to wait for a transaction to commit.
* @param maximumInFlight - The maximum number of transactions that can be in flight at once.
* @param sleepTime - The time to wait before retrying to get the sequence number.
*/
declare class AccountSequenceNumber {
readonly aptosConfig: AptosConfig;
readonly account: Account$1;
lastUncommintedNumber: bigint | null;
currentNumber: bigint | null;
/**
* We want to guarantee that we preserve ordering of workers to requests.
*
* `lock` is used to try to prevent multiple coroutines from accessing a shared resource at the same time,
* which can result in race conditions and data inconsistency.
* This code actually doesn't do it though, since we aren't giving out a slot, it is still somewhat a race condition.
*
* The ideal solution is likely that each thread grabs the next number from an incremental integer.
* When they complete, they increment that number and that entity is able to enter the `lock`.
* That would guarantee ordering.
*/
lock: boolean;
maxWaitTime: number;
maximumInFlight: number;
sleepTime: number;
/**
* Creates an instance of the class with the specified configuration and account details.
* This constructor initializes the necessary parameters for managing Aptos transactions.
*
* @param aptosConfig - The configuration settings for Aptos.
* @param account - The account associated with the Aptos transactions.
* @param maxWaitTime - The maximum time to wait for a transaction to be processed, in milliseconds.
* @param maximumInFlight - The maximum number of transactions that can be in flight at the same time.
* @param sleepTime - The time to sleep between transaction checks, in milliseconds.
*/
constructor(aptosConfig: AptosConfig, account: Account$1, maxWaitTime: number, maximumInFlight: number, sleepTime: number);
/**
* Returns the next available sequence number for this account.
* This function ensures that the sequence number is updated and synchronized, handling potential delays in transaction commits.
*
* @returns {BigInt} The next available sequence number.
*/
nextSequenceNumber(): Promise<bigint | null>;
/**
* Initializes this account with the sequence number on chain.
*
* @returns {Promise<void>} A promise that resolves when the account has been initialized.
*
* @throws {Error} Throws an error if the account information cannot be retrieved.
*/
initialize(): Promise<void>;
/**
* Updates this account's sequence number with the one on-chain.
*
* @returns The on-chain sequence number for this account.
*/
update(): Promise<bigint>;
/**
* Synchronizes the local sequence number with the sequence number on-chain for the specified account.
* This function polls the network until all submitted transactions have either been committed or until the maximum wait time has elapsed.
*
* @throws {Error} Throws an error if there is an issue synchronizing the account sequence number with the one on-chain.
*/
synchronize(): Promise<void>;
}
/**
* The AsyncQueue class is an async-aware data structure that provides a queue-like
* behavior for managing asynchronous tasks or operations.
* It allows to enqueue items and dequeue them asynchronously.
* This is not thread-safe, but it is async concurrency safe, and
* it does not guarantee ordering for those that call into and await on enqueue.
*/
declare class AsyncQueue<T> {
readonly queue: T[];
private pendingDequeue;
private cancelled;
/**
* Adds an item to the queue. If there are pending dequeued promises, it resolves the oldest promise with the enqueued item
* immediately; otherwise, it adds the item to the queue.
*
* @param item - The item to be added to the queue.
*/
enqueue(item: T): void;
/**
* Dequeues the next item from the queue and returns a promise that resolves to it.
* If the queue is empty, it creates a new promise that will be resolved when an item is enqueued.
*
* @returns Promise<T>
*/
dequeue(): Promise<T>;
/**
* Determine whether the queue is empty.
*
* @returns boolean - Returns true if the queue has no elements, otherwise false.
*/
isEmpty(): boolean;
/**
* Cancels all pending promises in the queue and rejects them with an AsyncQueueCancelledError.
* This ensures that any awaiting code can handle the cancellation appropriately.
*
* @returns {void}
*/
cancel(): void;
/**
* Determine whether the queue has been cancelled.
*
* @returns boolean - Returns true if the queue is cancelled, otherwise false.
*/
isCancelled(): boolean;
/**
* Retrieve the length of the pending dequeue.
*
* @returns number - The number of items currently in the pending dequeue.
*/
pendingDequeueLength(): number;
}
declare const promiseFulfilledStatus = "fulfilled";
/**
* Events emitted by the transaction worker during its operation, allowing the dapp to respond to various transaction states.
*/
declare enum TransactionWorkerEventsEnum {
TransactionSent = "transactionSent",
TransactionSendFailed = "transactionSendFailed",
TransactionExecuted = "transactionExecuted",
TransactionExecutionFailed = "transactionExecutionFailed",
ExecutionFinish = "executionFinish"
}
/**
* Defines the events emitted by the transaction worker during various stages of transaction processing. *
* @event transactionSent - Emitted when a transaction is successfully sent.
* @event transactionSendFailed - Emitted when sending a transaction fails.
* @event transactionExecuted - Emitted when a transaction is successfully executed.
* @event transactionExecutionFailed - Emitted when executing a transaction fails.
* @event executionFinish - Emitted when the execution process is finished.
*/
interface TransactionWorkerEvents {
transactionSent: (data: SuccessEventData) => void;
transactionSendFailed: (data: FailureEventData) => void;
transactionExecuted: (data: SuccessEventData) => void;
transactionExecutionFailed: (data: FailureEventData) => void;
executionFinish: (data: ExecutionFinishEventData) => void;
}
/**
* The payload for when the worker has finished its job.
*/
type ExecutionFinishEventData = {
message: string;
};
/**
* The payload for a success event.
*/
type SuccessEventData = {
message: string;
transactionHash: string;
};
/**
* The payload for a failure event.
*/
type FailureEventData = {
message: string;
error: string;
};
/**
* TransactionWorker provides a simple framework for receiving payloads to be processed.
*
* Once one `start()` the process and pushes a new transaction, the worker acquires
* the current account's next sequence number (by using the AccountSequenceNumber class),
* generates a signed transaction and pushes an async submission process into the `outstandingTransactions` queue.
* At the same time, the worker processes transactions by reading the `outstandingTransactions` queue
* and submits the next transaction to chain, it
* 1) waits for resolution of the submission process or get pre-execution validation error
* and 2) waits for the resolution of the execution process or get an execution error.
* The worker fires events for any submission and/or execution success and/or failure.
*/
declare class TransactionWorker extends EventEmitter<TransactionWorkerEvents> {
readonly aptosConfig: AptosConfig;
readonly account: Account$1;
readonly accountSequnceNumber: AccountSequenceNumber;
readonly taskQueue: AsyncQueue<() => Promise<void>>;
started: boolean;
/**
* transactions payloads waiting to be generated and signed
*
* TODO support entry function payload from ABI builder
*/
transactionsQueue: AsyncQueue<[InputGenerateTransactionPayloadData, InputGenerateTransactionOptions | undefined]>;
/**
* signed transactions waiting to be submitted
*/
outstandingTransactions: AsyncQueue<[Promise<PendingTransactionResponse>, bigint]>;
/**
* transactions that have been submitted to chain
*/
sentTransactions: Array<[string, bigint, any]>;
/**
* transactions that have been committed to chain
*/
executedTransactions: Array<[string, bigint, any]>;
/**
* Initializes a new instance of the class, providing a framework for receiving payloads to be processed.
*
* @param aptosConfig - A configuration object for Aptos.
* @param account - The account that will be used for sending transactions.
* @param maxWaitTime - The maximum wait time to wait before re-syncing the sequence number to the current on-chain state,
* default is 30 seconds.
* @param maximumInFlight - The maximum number of transactions that can be submitted per account, default is 100.
* @param sleepTime - The time to wait in seconds before re-evaluating if the maximum number of transactions are in flight,
* default is 10 seconds.
*/
constructor(aptosConfig: AptosConfig, account: Account$1, maxWaitTime?: number, maximumInFlight?: number, sleepTime?: number);
/**
* Submits the next transaction for the account by generating it with the current sequence number
* and adding it to the outstanding transaction queue for processing.
* This function continues to submit transactions until there are no more to process.
*
* @throws {Error} Throws an error if the transaction submission fails.
*/
submitNextTransaction(): Promise<void>;
/**
* Reads the outstanding transaction queue and submits the transactions to the chain.
* This function processes each transaction, checking their status and emitting events based on whether they were successfully
* sent or failed.
*
* @throws {Error} Throws an error if the process execution fails.
* @event TransactionWorkerEventsEnum.TransactionSent - Emitted when a transaction has been successfully committed to the chain.
* @event TransactionWorkerEventsEnum.TransactionSendFailed - Emitted when a transaction fails to commit, along with the error
* reason.
* @event TransactionWorkerEventsEnum.ExecutionFinish - Emitted when the execution of transactions is complete.
*/
processTransactions(): Promise<void>;
/**
* Once a transaction has been sent to the chain, this function checks for its execution status.
* @param sentTransaction - The transaction that was sent to the chain and is now waiting to be executed.
* @param sequenceNumber - The account's sequence number that was sent with the transaction.
*/
checkTransaction(sentTransaction: PromiseFulfilledResult<PendingTransactionResponse>, sequenceNumber: bigint): Promise<void>;
/**
* Pushes a transaction to the transactions queue for processing.
*
* @param transactionData - The transaction payload containing necessary details.
* @param transactionData.abi - For all entry function payloads, the ABI to skip remote ABI lookups.
* @param options - Optional parameters for transaction configuration.
* @param options.maxGasAmount - Maximum gas amount for the transaction.
* @param options.gasUnitPrice - Gas unit price for the transaction.
* @param options.expireTimestamp - Expiration timestamp on the transaction.
* @param options.accountSequenceNumber - The sequence number for the transaction.
*/
push(transactionData: InputGenerateTransactionPayloadData, options?: InputGenerateTransactionOptions): Promise<void>;
/**
* Generates a signed transaction that can be submitted to the chain.
*
* @param account - An Aptos account used as the sender of the transaction.
* @param sequenceNumber - A sequence number the transaction will be generated with.
* @returns A signed transaction object or undefined if the transaction queue is empty.
*/
generateNextTransaction(account: Account$1, sequenceNumber: bigint): Promise<SimpleTransaction | undefined>;
/**
* Starts transaction submission and processing by executing tasks from the queue until it is cancelled.
*
* @throws {Error} Throws an error if unable to start transaction batching.
*/
run(): Promise<void>;
/**
* Starts the transaction management process.
*
* @throws {Error} Throws an error if the worker has already started.
*/
start(): void;
/**
* Stops the transaction management process.
*
* @throws {Error} Throws an error if the worker has already stopped.
*/
stop(): void;
}
declare class TransactionManagement extends EventEmitter<TransactionWorkerEvents> {
account: Account$1;
transactionWorker: TransactionWorker;
readonly config: AptosConfig;
/**
* Initializes a new instance of the Aptos client with the provided configuration settings.
* This allows you to interact with the Aptos blockchain using the specified network and options.
*
* @param config - The configuration settings for the Aptos client.
* @param config.network - The network to connect to (e.g., TESTNET, MAINNET).
* @param config.nodeUrl - The URL of the Aptos node to connect to.
* @param config.account - Optional account settings for authentication.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* async function runExample() {
* // Create a configuration for the Aptos client
* const config = new AptosConfig({
* network: Network.TESTNET, // specify the network to use
* nodeUrl: "https://testnet.aptos.dev" // replace with your node URL
* });
*
* // Initialize the Aptos client with the configuration
* const aptos = new Aptos(config);
*
* console.log("Aptos client initialized successfully.");
* }
* runExample().catch(console.error);
* ```
*/
constructor(config: AptosConfig);
/**
* Initializes the transaction worker using the provided sender account and begins listening for events.
* This function is essential for setting up the transaction processing environment.
*
* @param args - The arguments for starting the transaction worker.
* @param args.sender - The sender account to sign and submit the transaction.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network, Account } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* const sender = Account.generate(); // Generate a new account for sending transactions
*
* // Start the transaction worker with the sender account
* aptos.start({ sender });
*
* console.log("Transaction worker started with sender:", sender.accountAddress);
* }
* runExample().catch(console.error);
* ```
*/
private start;
/**
* Pushes transaction data to the transaction worker for processing.
*
* @param args.data An array of transaction payloads to be processed.
* @param args.options Optional. Transaction generation configurations (excluding accountSequenceNumber).
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Prepare transaction payloads
* const payloads = [
* {}, // Build your first transaction payload
* {}, // Build your second transaction payload
* ];
*
* // Push transaction data to the worker
* aptos.push({
* data: payloads,
* {}, // Specify options as needed
* });
*
* console.log("Transaction data pushed successfully.");
* }
* runExample().catch(console.error);
* ```
*/
private push;
/**
* Starts listening to transaction worker events, allowing the application to respond to transaction status changes.
* This function enables the application to handle events such as transaction sent, execution success, or failure.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Register to listen for transaction events
* aptos.registerToEvents();
*
* // You can send a transaction here to see the events in action
* const sender = Account.generate(); // replace with a real account
* const destination = Account.generate(); // replace with a real account
*
* const transaction = await aptos.transaction.build.simple({
* sender: sender.accountAddress,
* data: {
* function: "0x1::aptos_account::transfer",
* functionArguments: [destination.accountAddress, 100],
* },
* });
*
* await aptos.transaction.send(transaction);
*
* console.log("Transaction sent and events registered.");
* }
* runExample().catch(console.error);
* ```
*/
private registerToEvents;
/**
* Send batch transactions for a single account.
*
* This function uses a transaction worker that receives payloads to be processed
* and submitted to chain.
* Note that this process is best for submitting multiple transactions that
* don't rely on each other, i.e. batch funds, batch token mints, etc.
*
* If any worker failure, the functions throws an error.
*
* @param args.sender The sender account to sign and submit the transaction
* @param args.data An array of transaction payloads
* @param args.options optional. Transaction generation configurations (excluding accountSequenceNumber)
*
* @return void. Throws if any error
*/
forSingleAccount(args: {
sender: Account$1;
data: InputGenerateTransactionPayloadData[];
options?: Omit<InputGenerateTransactionOptions, "accountSequenceNumber">;
}): void;
}
/**
* Represents a transaction in the Aptos blockchain,
* providing methods to build, simulate, submit, and manage transactions.
* This class encapsulates functionalities for querying transaction details,
* estimating gas prices, signing transactions, and handling transaction states.
*
* This class is used as part of the Aptos object, so should be called like so:
* @example
* ```typescript
* import { Account, Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const APTOS_COIN = "0x1::aptos_coin::AptosCoin";
* const COIN_STORE = `0x1::coin::CoinStore<${APTOS_COIN}>`;
* const ALICE_INITIAL_BALANCE = 100_000_000;
* const TRANSFER_AMOUNT = 100;
*
* async function example() {
* console.log(
* "This example will create two accounts (Alice and Bob), fund them, and transfer between them.",
* );
*
* // Set up the client
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* // Generate two account credentials
* // Each account has a private key, a public key, and an address
* const alice = Account.generate();
* const bob = Account.generate();
*
* console.log("=== Addresses ===\n");
* console.log(`Alice's address is: ${alice.accountAddress}`);
* console.log(`Bob's address is: ${bob.accountAddress}`);
*
* // Fund the accounts using a faucet
* console.log("\n=== Funding accounts ===\n");
*
* await aptos.fundAccount({
* accountAddress: alice.accountAddress,
* amount: ALICE_INITIAL_BALANCE,
* });
*
* // Send a transaction from Alice's account to Bob's account
* const txn = await aptos.transaction.build.simple({
* sender: alice.accountAddress,
* data: {
* // All transactions on Aptos are implemented via smart contracts.
* function: "0x1::aptos_account::transfer",
* functionArguments: [bob.accountAddress, 100],
* },
* });
*
* console.log("\n=== Transfer transaction ===\n");
* // Both signs and submits
* const committedTxn = await aptos.signAndSubmitTransaction({
* signer: alice,
* transaction: txn,
* });
* // Waits for Aptos to verify and execute the transaction
* const executedTransaction = await aptos.waitForTransaction({
* transactionHash: committedTxn.hash,
* });
* console.log("Transaction hash:", executedTransaction.hash);
*
* console.log("\n=== Balances after transfer ===\n");
* const newAliceAccountBalance = await aptos.getAccountResource({
* accountAddress: alice.accountAddress,
* resourceType: COIN_STORE,
* });
* const newAliceBalance = Number(newAliceAccountBalance.coin.value);
* console.log(`Alice's balance is: ${newAliceBalance}`);
*
* const newBobAccountBalance = await aptos.getAccountResource({
* accountAddress: bob.accountAddress,
* resourceType: COIN_STORE,
* });
* const newBobBalance = Number(newBobAccountBalance.coin.value);
* console.log(`Bob's balance is: ${newBobBalance}`);
* }
*
* example();
* ```
*/
declare class Transaction {
readonly config: AptosConfig;
readonly build: Build;
readonly simulate: Simulate;
readonly submit: Submit;
readonly batch: TransactionManagement;
/**
* Creates an instance of the Aptos client with the specified configuration.
* This allows you to interact with the Aptos blockchain using the provided settings.
*
* @param config - The configuration settings for the Aptos client.
* @param config.network - The network to connect to (e.g., Testnet, Mainnet).
* @param config.nodeUrl - The URL of the Aptos node to connect to.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* async function runExample() {
* // Create a new Aptos client instance
* const config = new AptosConfig({ network: Network.TESTNET }); // Specify the network
* const aptos = new Aptos(config);
*
* console.log("Aptos client created successfully:", aptos);
* }
* runExample().catch(console.error);
* ```
*/
constructor(config: AptosConfig);
/**
* Queries on-chain transactions, excluding pending transactions.
* Use this function to retrieve historical transactions from the blockchain.
*
* @param args Optional parameters for pagination.
* @param args.options Optional pagination options.
* @param args.options.offset The number of the transaction to start with.
* @param args.options.limit The number of results to return.
*
* @returns An array of on-chain transactions.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Fetch transactions with pagination
* const transactions = await aptos.getTransactions({
* options: {
* offset: 0, // Start from the first transaction
* limit: 10, // Limit to 10 results
* },
* });
*
* console.log(transactions);
* }
* runExample().catch(console.error);
* ```
*/
getTransactions(args?: {
options?: PaginationArgs;
}): Promise<TransactionResponse[]>;
/**
* Queries on-chain transaction by version. This function will not return pending transactions.
*
* @param args - The arguments for querying the transaction.
* @param args.ledgerVersion - Transaction version is an unsigned 64-bit number.
* @returns On-chain transaction. Only on-chain transactions have versions, so this
* function cannot be used to query pending transactions.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Fetching a transaction by its version
* const transaction = await aptos.getTransactionByVersion({ ledgerVersion: 1 }); // replace 1 with a real version
* console.log(transaction);
* }
* runExample().catch(console.error);
* ```
*/
getTransactionByVersion(args: {
ledgerVersion: AnyNumber;
}): Promise<TransactionResponse>;
/**
* Queries on-chain transactions by their transaction hash, returning both pending and committed transactions.
*
* @param args - The arguments for querying the transaction.
* @param args.transactionHash - The transaction hash should be a hex-encoded bytes string with a 0x prefix.
* @returns The transaction from the mempool (pending) or the on-chain (committed) transaction.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Fetch a transaction by its hash
* const transaction = await aptos.getTransactionByHash({ transactionHash: "0x123" }); // replace with a real transaction hash
*
* console.log(transaction);
* }
* runExample().catch(console.error);
* ```
*/
getTransactionByHash(args: {
transactionHash: HexInput;
}): Promise<TransactionResponse>;
/**
* Defines if the specified transaction is currently in a pending state.
* This function helps you determine the status of a transaction using its hash.
*
* @param args - The arguments for the function.
* @param args.transactionHash - A hash of the transaction in hexadecimal format.
* @returns `true` if the transaction is in a pending state and `false` otherwise.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Check if the transaction is pending using its hash
* const isPendingTransaction = await aptos.isPendingTransaction({ transactionHash: "0x123" }); // replace with a real transaction hash
* console.log("Is the transaction pending?", isPendingTransaction);
* }
* runExample().catch(console.error);
* ```
*/
isPendingTransaction(args: {
transactionHash: HexInput;
}): Promise<boolean>;
/**
* Waits for a transaction to move past the pending state and provides the transaction response.
* There are 4 cases.
* 1. Transaction is successfully processed and committed to the chain.
* - The function will resolve with the transaction response from the API.
* 2. Transaction is rejected for some reason, and is therefore not committed to the blockchain.
* - The function will throw an AptosApiError with an HTTP status code indicating some problem with the request.
* 3. Transaction is committed but execution failed, meaning no changes were
* written to the blockchain state.
* - If `checkSuccess` is true, the function will throw a FailedTransactionError
* If `checkSuccess` is false, the function will resolve with the transaction response where the `success` field is false.
* 4. Transaction does not move past the pending state within `args.options.timeoutSecs` seconds.
* - The function will throw a WaitForTransactionError
*
* @param args.transactionHash - The hash of a transaction previously submitted to the blockchain.
* @param args.options - Optional parameters for waiting behavior.
* @param args.options.timeoutSecs - Timeout in seconds. Defaults to 20 seconds.
* @param args.options.checkSuccess - A boolean which controls whether the function will error if the transaction failed.
* Defaults to true.
* @returns The transaction on-chain response.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Wait for a transaction to complete using its hash
* const transactionHash = "0x123"; // replace with a real transaction hash
* const transactionResponse = await aptos.waitForTransaction({
* transactionHash,
* options: {
* timeoutSecs: 30, // specify your own timeout if needed
* checkSuccess: true,
* },
* });
*
* console.log(transactionResponse);
* }
* runExample().catch(console.error);
* ```
*/
waitForTransaction(args: {
transactionHash: HexInput;
options?: WaitForTransactionOptions;
}): Promise<CommittedTransactionResponse>;
/**
* Estimates the gas unit price required to process a transaction on the Aptos blockchain in a timely manner.
* This helps users to understand the cost associated with their transactions.
* {@link https://api.mainnet.aptoslabs.com/v1/spec#/operations/estimate_gas_price}
*
* @returns An object containing the estimated gas price.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET }); // Specify your network
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Getting the gas price estimation
* const gasPriceEstimation = await aptos.getGasPriceEstimation();
*
* console.log("Estimated Gas Price:", gasPriceEstimation);
* }
* runExample().catch(console.error);
* ```
*/
getGasPriceEstimation(): Promise<GasEstimation>;
/**
* Returns a signing message for a transaction, allowing a user to sign it using their preferred method before submission to the network.
*
* @param args - The arguments for obtaining the signing message.
* @param args.transaction - A raw transaction for signing elsewhere.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* const transaction = await aptos.transaction.build.simple({
* sender: "0x1", // replace with a real sender address
* data: {
* function: "0x1::aptos_account::transfer",
* functionArguments: ["0x2", 100], // replace with a real destination address
* },
* });
*
* const message = await aptos.getSigningMessage({ transaction });
* console.log(message);
* }
* runExample().catch(console.error);
* ```
*/
getSigningMessage(args: {
transaction: AnyRawTransaction;
}): Uint8Array;
/**
* Generates a transaction to publish a Move package to the blockchain.
* This function helps you create a transaction that can be simulated or submitted to the chain for publishing a package.
*
* To get the `metadataBytes` and `byteCode`, can compile using Aptos CLI with command
* `aptos move compile --save-metadata ...`,
*
* {@link https://aptos.dev/tutorials/your-first-dapp/#step-4-publish-a-move-module}
*
* @param args The arguments for publishing the package.
* @param args.account The publisher account.
* @param args.metadataBytes The package metadata bytes.
* @param args.moduleBytecode An array of the bytecode of each module in the package in compiler output order.
* @param args.options Optional settings for generating the transaction.
*
* @returns A SimpleTransaction that can be simulated or submitted to the chain.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Replace with a real account address
* const account = "0x1";
* const metadataBytes = "0x..."; // replace with real metadata bytes
* const byteCode = "0x..."; // replace with real module bytecode
*
* const transaction = await aptos.publishPackageTransaction({
* account,
* metadataBytes,
* moduleBytecode: [byteCode],
* });
*
* console.log(transaction);
* }
* runExample().catch(console.error);
* ```
*/
publishPackageTransaction(args: {
account: AccountAddressInput;
metadataBytes: HexInput;
moduleBytecode: Array<HexInput>;
options?: InputGenerateTransactionOptions;
}): Promise<SimpleTransaction>;
/**
* Rotate an account's authentication key. After rotation, only the new private key can be used to sign transactions for the account.
* Note: Only legacy Ed25519 scheme is supported for now.
* More info: {@link https://aptos.dev/guides/account-management/key-rotation/}
*
* @param args The arguments for rotating the auth key.
* @param args.fromAccount The account to rotate the auth key for.
* @param args.toNewPrivateKey The new private key to rotate to.
*
* @returns PendingTransactionResponse
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network, Account, PrivateKey } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Rotate the authentication key for an account
* const response = await aptos.rotateAuthKey({
* // replace with a real account
* fromAccount: Account.generate(),
* // replace with a real private key
* toNewPrivateKey: new PrivateKey("0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef"),
* });
*
* console.log(response);
* }
* runExample().catch(console.error);
* ```
*/
rotateAuthKey(args: {
fromAccount: Account$1;
toNewPrivateKey: PrivateKey;
}): Promise<TransactionResponse>;
/**
* Sign a transaction that can later be submitted to the chain.
* This function is essential for ensuring the authenticity of the transaction by using the provided account's signing capabilities.
*
* @param args - The arguments for signing the transaction.
* @param args.signer - The account that will sign the transaction.
* @param args.transaction - A raw transaction to sign.
*
* @returns AccountAuthenticator - The authenticator for the signed transaction.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* const sender = Account.generate(); // Generate a new account for signing
* const transaction = await aptos.transaction.build.simple({
* sender: sender.accountAddress,
* data: {
* function: "0x1::aptos_account::transfer",
* functionArguments: [ "0x1", 100 ], // replace with a real account address and amount
* },
* });
*
* const signedTransaction = await aptos.transaction.sign({
* signer: sender,
* transaction,
* }); // Sign the transaction
*
* console.log("Signed Transaction:", signedTransaction);
* }
* runExample().catch(console.error);
* ```
*/
sign(args: {
signer: Account$1;
transaction: AnyRawTransaction;
}): AccountAuthenticator;
/**
* Sign a transaction as a fee payer that can later be submitted to the chain.
* This function ensures that the transaction is marked with the fee payer's address, allowing it to be processed correctly.
*
* @param args - The arguments for signing the transaction.
* @param args.signer - The fee payer signer account.
* @param args.transaction - A raw transaction to sign on. This transaction must include a `feePayerAddress` property.
*
* @returns AccountAuthenticator - The authenticator for the signed transaction.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* const sender = Account.generate(); // Generate a new account for the fee payer
* const transaction = await aptos.transaction.build.simple({
* // All transactions on Aptos are implemented via smart contracts.
* function: "0x1::aptos_account::transfer",
* functionArguments: [sender.accountAddress, 100],
* feePayerAddress: sender.accountAddress, // Set the fee payer address
* });
*
* const signedTransaction = await aptos.transaction.signAsFeePayer({
* signer: sender,
* transaction,
* });
*
* console.log("Signed transaction as fee payer:", signedTransaction);
* }
* runExample().catch(console.error);
* ```
*/
signAsFeePayer(args: {
signer: Account$1;
transaction: AnyRawTransaction;
}): AccountAuthenticator;
/**
* @deprecated Prefer to use `aptos.transaction.batch.forSingleAccount()`
*
* Batch transactions for a single account by submitting multiple transaction payloads.
* This function is useful for efficiently processing and submitting transactions that do not depend on each other, such as
* batch funding or batch token minting.
*
* @param args - The arguments for batching transactions.
* @param args.sender - The sender account to sign and submit the transactions.
* @param args.data - An array of transaction payloads to be processed.
* @param args.options - Optional. Transaction generation configurations (excluding accountSequenceNumber).
*
* @throws Error if any worker failure occurs during submission.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network, Account } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
* const sender = Account.generate(); // Generate a new account for sending transactions
*
* async function runExample() {
* const transactions = [
* { }, // Build your first transaction payload
* { }, // Build your second transaction payload
* ];
*
* // Batch transactions for the single account
* await aptos.batchTransactionsForSingleAccount({
* sender,
* data: transactions,
* });
*
* console.log("Batch transactions submitted successfully.");
* }
* runExample().catch(console.error);
* ```
*/
batchTransactionsForSingleAccount(args: {
sender: Account$1;
data: InputGenerateTransactionPayloadData[];
options?: Omit<InputGenerateTransactionOptions, "accountSequenceNumber">;
}): Promise<void>;
/**
* Sign and submit a single signer transaction to the blockchain.
* This function allows you to execute a transaction after signing it with the specified account.
*
* @param args The arguments for signing and submitting the transaction.
* @param args.signer The signer account to sign the transaction.
* @param args.transaction An instance of a RawTransaction, plus optional secondary/fee payer addresses.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* const sender = Account.generate(); // Generate a new account for sending the transaction
* const transaction = await aptos.transaction.build.simple({
* sender: sender.accountAddress,
* data: {
* function: "0x1::aptos_account::transfer",
* functionArguments: [ "0x1", 100 ], // replace with a real account address
* },
* });
*
* // Sign and submit the transaction
* const pendingTransaction = await aptos.signAndSubmitTransaction({
* signer: sender,
* transaction,
* });
*
* console.log(pendingTransaction);
* }
* runExample().catch(console.error);
* ```
* @return PendingTransactionResponse
*/
signAndSubmitTransaction(args: FeePayerOrFeePayerAuthenticatorOrNeither & {
signer: Account$1;
transaction: AnyRawTransaction;
}): Promise<PendingTransactionResponse>;
/**
* Sign and submit a single signer transaction as the fee payer to chain given an authenticator by the sender of the transaction.
*
* @param args.feePayer The fee payer account to sign the transaction
* @param args.senderAuthenticator The AccountAuthenticator signed by the sender of the transaction
* @param args.transaction An instance of a RawTransaction, plus optional secondary/fee payer addresses
*
* @example
* const transaction = await aptos.transaction.build.simple({sender: alice.accountAddress, feePayer: true ...})
* const senderAuthenticator = alice.signTransactionWithAuthenticator(transaction)
* const pendingTransaction = await aptos.signAndSubmitAsFeePayer({
* senderAuthenticator,
* feePayer: bob,
* transaction,
* })
*
* @return PendingTransactionResponse
*/
signAndSubmitAsFeePayer(args: {
feePayer: Account$1;
senderAuthenticator: AccountAuthenticator;
transaction: AnyRawTransaction;
}): Promise<PendingTransactionResponse>;
}
/**
* A class to query all `Table` Aptos related queries.
*/
declare class Table {
readonly config: AptosConfig;
/**
* Initializes a new instance of the Aptos client with the specified configuration.
* This allows you to interact with the Aptos blockchain using the provided settings.
*
* @param config - The configuration settings for the Aptos client.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* async function runExample() {
* // Create a new Aptos client with testnet configuration
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* console.log("Aptos client initialized:", aptos);
* }
* runExample().catch(console.error);
* ```
*/
constructor(config: AptosConfig);
/**
* Queries for a specific item in a table identified by the handle and the key for the item.
* This function allows you to retrieve structured data from a table in the Aptos blockchain.
*
* @param args.handle A pointer to where that table is stored.
* @param args.data Object that describes the table item, including key and value types.
* @param args.data.key_type The Move type of the table key.
* @param args.data.value_type The Move type of the table value.
* @param args.data.key The value of the table key.
* @param args.options.ledgerVersion The ledger version to query; if not provided, it will get the latest version.
*
* @returns Table item value rendered in JSON.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Retrieve a table item from the Aptos blockchain
* const tableItem = await aptos.getTableItem({
* handle: "0x1b854694ae746cdbd8d44186ca4929b2b337df21d1c74633be19b2710552fdca",
* data: {
* key_type: "address", // Move type of table key
* value_type: "u128", // Move type of table value
* key: "0x619dc29a0aac8fa146714058e8dd6d2d0f3bdf5f6331907bf91f3acd81e6935" // Value of table key
* },
* });
*
* console.log(tableItem);
* }
* runExample().catch(console.error);
* ```
*/
getTableItem<T>(args: {
handle: string;
data: TableItemRequest;
options?: LedgerVersionArg;
}): Promise<T>;
/**
* Queries for table items data with optional filtering and pagination.
* This function allows you to retrieve specific data from a table based on provided criteria.
*
* @param args - The arguments for querying table items data.
* @param args.minimumLedgerVersion - Optional minimum ledger version to wait for before querying.
* @param args.options - Optional parameters for pagination and filtering.
* @param args.options.where - Conditions to filter the response.
* @param args.options.offset - The number of items to skip before starting to collect the result set.
* @param args.options.limit - The maximum number of items to return.
* @param args.options.orderBy - The criteria to order the results.
*
* Note: This query calls the indexer server.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Retrieve table items data with specific filtering options
* const data = await aptos.getTableItemsData({
* minimumLedgerVersion: 1, // specify your own minimum ledger version if needed
* options: {
* where: {
* table_handle: { _eq: "0x1b854694ae746cdbd8d44186ca4929b2b337df21d1c74633be19b2710552fdca" },
* transaction_version: { _eq: "0" }
* },
* limit: 10, // specify your own limit if needed
* },
* });
*
* console.log(data);
* }
* runExample().catch(console.error);
* ```
*
* @returns GetTableItemsDataResponse
*/
getTableItemsData(args: {
minimumLedgerVersion?: AnyNumber;
options?: PaginationArgs & WhereArg<TableItemsBoolExp> & OrderByArg<GetTableItemsDataResponse[0]>;
}): Promise<GetTableItemsDataResponse>;
/**
* Queries for the metadata of table items, allowing for filtering and pagination.
*
* @param args - The parameters for the query.
* @param args.minimumLedgerVersion - Optional minimum ledger version to wait for before querying.
* @param args.options - Optional parameters for pagination and filtering.
* @param args.options.where - Conditions to filter the response.
* @param args.options.offset - The offset for pagination.
* @param args.options.limit - The maximum number of items to return.
* @param args.options.orderBy - The order in which to return the items.
*
* Note that this query calls the indexer server.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Fetching table items metadata with a filter condition
* const data = await aptos.getTableItemsMetadata({
* minimumLedgerVersion: 1, // specify your own minimum ledger version if needed
* options: {
* where: { handle: { _eq: "0x1b854694ae746cdbd8d44186ca4929b2b337df21d1c74633be19b2710552fdca" } },
* limit: 10, // specify your own limit if needed
* },
* });
*
* console.log(data);
* }
* runExample().catch(console.error);
* ```
*
* @returns GetTableItemsMetadataResponse
*/
getTableItemsMetadata(args: {
minimumLedgerVersion?: AnyNumber;
options?: PaginationArgs & WhereArg<TableMetadatasBoolExp> & OrderByArg<GetTableItemsMetadataResponse[0]>;
}): Promise<GetTableItemsMetadataResponse>;
}
/**
* A class to query all `Keyless` related queries on Aptos.
*
* More documentation on how to integrate Keyless Accounts see the below
* [Aptos Keyless Integration Guide](https://aptos.dev/guides/keyless-accounts/#aptos-keyless-integration-guide).
*/
declare class Keyless {
readonly config: AptosConfig;
/**
* Initializes a new instance of the Aptos class with the provided configuration.
* This allows you to interact with the Aptos blockchain using the specified network settings.
*
* @param config - The configuration settings for connecting to the Aptos network.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* async function runExample() {
* // Create a new configuration for the Aptos client
* const config = new AptosConfig({ network: Network.TESTNET }); // Specify your desired network
*
* // Initialize the Aptos client with the configuration
* const aptos = new Aptos(config);
*
* console.log("Aptos client initialized:", aptos);
* }
* runExample().catch(console.error);
* ```
*/
constructor(config: AptosConfig);
/**
* Fetches the pepper from the Aptos pepper service API.
*
* @param args - The arguments for fetching the pepper.
* @param args.jwt - JWT token.
* @param args.ephemeralKeyPair - The EphemeralKeyPair used to generate the nonce in the JWT token.
* @param args.derivationPath - A derivation path used for creating multiple accounts per user via the BIP-44 standard. Defaults
* to "m/44'/637'/0'/0'/0".
* @returns The pepper which is a Uint8Array of length 31.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* const ephemeralKeyPair = new EphemeralKeyPair(); // create a new ephemeral key pair
* const jwt = "your_jwt_token"; // replace with a real JWT token
*
* // Fetching the pepper using the provided JWT and ephemeral key pair
* const pepper = await aptos.getPepper({
* jwt,
* ephemeralKeyPair,
* // derivationPath: "m/44'/637'/0'/0'/0" // specify your own if needed
* });
*
* console.log("Fetched pepper:", pepper);
* }
* runExample().catch(console.error);
* ```
*/
getPepper(args: {
jwt: string;
ephemeralKeyPair: EphemeralKeyPair;
derivationPath?: string;
}): Promise<Uint8Array>;
/**
* Fetches a proof from the Aptos prover service API.
*
* @param args - The arguments for fetching the proof.
* @param args.jwt - JWT token.
* @param args.ephemeralKeyPair - The EphemeralKeyPair used to generate the nonce in the JWT token.
* @param args.pepper - The pepper used for the account. If not provided, it will be fetched from the Aptos pepper service.
* @param args.uidKey - A key in the JWT token to use to set the uidVal in the IdCommitment.
*
* @returns The proof which is represented by a ZeroKnowledgeSig.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network, EphemeralKeyPair, getPepper } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* const jwt = "your_jwt_token"; // replace with a real JWT token
* const ephemeralKeyPair = new EphemeralKeyPair(); // create a new ephemeral key pair
*
* // Fetch the proof using the getProof function
* const proof = await aptos.getProof({
* jwt,
* ephemeralKeyPair,
* pepper: await getPepper({}), // fetch the pepper if not provided
* uidKey: "sub", // specify the uid key
* });
*
* console.log("Fetched proof:", proof);
* }
* runExample().catch(console.error);
* ```
*/
getProof(args: {
jwt: string;
ephemeralKeyPair: EphemeralKeyPair;
pepper?: HexInput;
uidKey?: string;
}): Promise<ZeroKnowledgeSig>;
deriveKeylessAccount(args: {
jwt: string;
ephemeralKeyPair: EphemeralKeyPair;
uidKey?: string;
pepper?: HexInput;
proofFetchCallback?: ProofFetchCallback;
}): Promise<KeylessAccount>;
deriveKeylessAccount(args: {
jwt: string;
ephemeralKeyPair: EphemeralKeyPair;
jwkAddress: AccountAddressInput;
uidKey?: string;
pepper?: HexInput;
proofFetchCallback?: ProofFetchCallback;
}): Promise<FederatedKeylessAccount>;
/**
* This installs a set of FederatedJWKs at an address for a given iss.
*
* It will fetch the JSON Web Keyset (JWK) set from the well-known endpoint and update the FederatedJWKs at the sender's address
* to reflect it.
*
* @param args.sender The account that will install the JWKs
* @param args.iss the iss claim of the federated OIDC provider.
* @param args.jwksUrl the URL to find the corresponding JWKs. For supported IDP providers this parameter in not necessary.
*
* @returns The pending transaction that results from submission.
*/
updateFederatedKeylessJwkSetTransaction(args: {
sender: Account$1;
iss: string;
jwksUrl?: string;
options?: InputGenerateTransactionOptions;
}): Promise<SimpleTransaction>;
}
/**
* A class to query all `Object` related queries on Aptos.
*/
declare class AptosObject {
readonly config: AptosConfig;
/**
* Creates an instance of the Aptos client with the provided configuration.
* This allows interaction with the Aptos blockchain using the specified settings.
*
* @param config - The configuration settings for the Aptos client.
* @param config.network - The network to connect to (e.g., mainnet, testnet).
* @param config.nodeUrl - The URL of the Aptos node to connect to.
* @param config.faucetUrl - The URL of the faucet for funding accounts (optional).
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* async function runExample() {
* // Create a configuration for the Aptos client
* const config = new AptosConfig({
* network: Network.TESTNET, // Specify the desired network
* nodeUrl: "https://testnet.aptos.dev", // Replace with your node URL
* });
*
* // Create an instance of the Aptos client
* const aptos = new Aptos(config);
*
* console.log("Aptos client created successfully", aptos);
* }
* runExample().catch(console.error);
* ```
*/
constructor(config: AptosConfig);
/**
* Fetches the object data based on the specified object address.
*
* @param args.objectAddress - The object address to retrieve data for.
* @param args.minimumLedgerVersion - Optional minimum ledger version to wait for.
* @param args.options - Optional configuration options for pagination and ordering.
*
* @returns The object data corresponding to the provided address.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* const config = new AptosConfig({ network: Network.TESTNET });
* const aptos = new Aptos(config);
*
* async function runExample() {
* // Fetching object data by object address
* const objectData = await aptos.getObjectDataByObjectAddress({
* objectAddress: "0x1", // replace with a real object address
* });
*
* console.log(objectData);
* }
* runExample().catch(console.error);
* ```
*/
getObjectDataByObjectAddress(args: {
objectAddress: AccountAddressInput;
minimumLedgerVersion?: AnyNumber;
options?: PaginationArgs & OrderByArg<GetObjectDataQueryResponse[0]>;
}): Promise<GetObjectDataQueryResponse[0]>;
}
/**
* The main entry point for interacting with the Aptos APIs,
* providing access to various functionalities organized into
* distinct namespaces.
*
* To utilize the SDK, instantiate a new Aptos object to gain
* access to the complete range of SDK features.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* async function runExample() {
* // Create a configuration for connecting to the Aptos testnet
* const config = new AptosConfig({ network: Network.TESTNET });
*
* // Initialize the Aptos client with the configuration
* const aptos = new Aptos(config);
*
* console.log("Aptos client initialized:", aptos);
* }
* runExample().catch(console.error);
* ```
*/
declare class Aptos {
readonly config: AptosConfig;
readonly account: Account;
readonly ans: ANS;
readonly coin: Coin;
readonly digitalAsset: DigitalAsset;
readonly event: Event;
readonly faucet: Faucet;
readonly fungibleAsset: FungibleAsset;
readonly general: General;
readonly staking: Staking;
readonly transaction: Transaction;
readonly table: Table;
readonly keyless: Keyless;
readonly object: AptosObject;
/**
* Initializes a new instance of the Aptos client with the provided configuration settings.
* This allows you to interact with various Aptos functionalities such as accounts, transactions, and events.
*
* @param settings - Configuration settings for the Aptos client.
*
* @example
* ```typescript
* import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
*
* async function runExample() {
* // Create a new Aptos client with default settings
* const config = new AptosConfig({ network: Network.TESTNET }); // Specify your own settings if needed
* const aptos = new Aptos(config);
*
* console.log("Aptos client initialized:", aptos);
* }
* runExample().catch(console.error);
* ```
*/
constructor(settings?: AptosConfig);
}
interface Aptos extends Account, ANS, Coin, DigitalAsset, Event, Faucet, FungibleAsset, General, Keyless, Staking, Table, AptosObject, Omit<Transaction, "build" | "simulate" | "submit" | "batch"> {
}
type DeserializableClass<T extends Serializable> = {
/**
* Deserializes a serialized object using the provided deserializer.
* This function allows you to reconstruct an object from its serialized form.
*
* @param deserializer - An instance of the Deserializer used to read the serialized data.
*/
deserialize(deserializer: Deserializer): T;
};
/**
* Normalizes an instance of a class by deserializing it from its byte representation.
* This function allows the `instanceof` operator to work correctly when the input objects originate from a different bundle.
*
* @param cls - The class of the object to normalize.
* @param value - The instance to normalize.
*/
declare function normalizeBundle<T extends Serializable>(cls: DeserializableClass<T>, value: T): T;
/**
* Sleep for the specified amount of time in milliseconds.
* This function can be used to introduce delays in asynchronous operations.
*
* @param timeMs - The time in milliseconds to sleep.
*/
declare function sleep(timeMs: number): Promise<null>;
/**
* Get the error message from an unknown error.
*
* @param error The error to get the message from
* @returns The error message
*/
declare function getErrorMessage(error: unknown): string;
declare const nowInSeconds: () => number;
/**
* Floors the given timestamp to the nearest whole hour.
* This function is useful for normalizing timestamps to hourly intervals.
*
* @param timestampInSeconds - The timestamp in seconds to be floored.
*/
declare function floorToWholeHour(timestampInSeconds: number): number;
/**
* Decodes a base64 URL-encoded string into its original form.
* This function is useful for converting base64 URL-encoded data back to a readable format.
*
* @param base64Url - The base64 URL-encoded string to decode.
* @returns The decoded string.
*/
declare function base64UrlDecode(base64Url: string): string;
/**
* Amount is represented in the smallest unit format on chain, this function converts
* a human-readable amount format to the smallest unit format
* @example
* human-readable amount format: 500
* on chain amount format when decimal is 8: 50000000000
*
* @param value The value in human-readable format
* @param decimal The token decimal
* @returns The value in the smallest units
*/
declare const convertAmountFromHumanReadableToOnChain: (value: number, decimal: number) => number;
/**
* Amount is represented in the smallest unit format on chain, this function converts
* the smallest unit format to a human-readable amount format
* @example
* human-readable amount format: 500
* on chain amount format when decimal is 8: 50000000000
*
* @param value The value in human-readable format
* @param decimal The token decimal
* @returns The value in the smallest units
*/
declare const convertAmountFromOnChainToHumanReadable: (value: number, decimal: number) => number;
/**
* Convert an encoded struct to a MoveStructId.
*
* @example
* const structObj = {
* account_address: "0x1",
* module_name: "0x6170746f735f636f696e",
* struct_name: "0x4170746f73436f696e",
* };
* // structId is "0x1::aptos_coin::AptosCoin"
* const structId = parseEncodedStruct(structObj);
*
* @param structObj The struct with account_address, module_name, and struct_name properties
* @returns The MoveStructId
*/
declare const parseEncodedStruct: (structObj: {
account_address: string;
module_name: string;
struct_name: string;
}) => MoveStructId;
/**
* Determines whether the given object is an encoded struct type with the following properties:
* - account_address: string
* - module_name: string
* - struct_name: string
*
* @param structObj The object to check
* @returns Whether the object is an encoded struct type
*/
declare const isEncodedStruct: (structObj: any) => structObj is {
account_address: string;
module_name: string;
struct_name: string;
};
/**
* Sends a request using the specified options and returns the response.
*
* @param options - The options for the request.
* @param options.url - The URL to send the request to.
* @param options.method - The HTTP method to use for the request.
* @param options.body - The body of the request.
* @param options.contentType - The content type of the request.
* @param options.params - The query parameters to include in the request.
* @param options.overrides - Additional overrides for the request.
* @param options.overrides.HEADERS - Custom headers to include in the request.
* @param options.overrides.AUTH_TOKEN - The authorization token for the request.
* @param options.overrides.API_KEY - The API key for the request.
* @param options.originMethod - The origin method for the request.
* @param client - The client used to make the request.
*
* @returns The response from the request.
*/
declare function request<Req, Res>(options: ClientRequest<Req>, client: Client): Promise<ClientResponse<Res>>;
/**
* The main function to use when making an API request, returning the response or throwing an AptosApiError on failure.
*
* @param aptosRequestOpts - Options for the Aptos request, including the URL and path.
* @param aptosConfig - The configuration information for the SDK client instance.
* @param apiType - The type of API being accessed, which determines how the response is handled.
* @returns The response from the API request or throws an AptosApiError if the request fails.
*/
declare function aptosRequest<Req extends {}, Res extends {}>(aptosRequestOpts: AptosRequest, aptosConfig: AptosConfig, apiType: AptosApiType): Promise<AptosResponse<Req, Res>>;
/**
* Options for making a GET request, including configuration for the API client.
*/
type GetRequestOptions = {
/**
* The config for the API client
*/
aptosConfig: AptosConfig;
/**
* The type of API endpoint to call e.g. fullnode, indexer, etc
*/
type: AptosApiType;
/**
* The name of the API method
*/
originMethod: string;
/**
* The URL path to the API method
*/
path: string;
/**
* The content type of the request body
*/
contentType?: MimeType;
/**
* The accepted content type of the response of the API
*/
acceptType?: MimeType;
/**
* The query parameters for the request
*/
params?: Record<string, string | AnyNumber | boolean | undefined>;
/**
* Specific client overrides for this request to override aptosConfig
*/
overrides?: ClientConfig;
};
/**
* Options for making a request to the Aptos API, excluding the "type" field.
*/
type GetAptosRequestOptions = Omit<GetRequestOptions, "type">;
/**
* Executes a GET request to retrieve data based on the provided options.
*
* @param options - The options for the GET request.
* @param options.aptosConfig - The configuration object for Aptos requests.
* @param options.overrides - Optional overrides for the request configuration.
* @param options.params - Query parameters to include in the request.
* @param options.contentType - The content type of the request.
* @param options.acceptType - The accepted response type.
* @param options.path - The specific path for the request.
* @param options.originMethod - The original method of the request.
* @param options.type - The type of request being made.
* @returns The response from the GET request.
*/
declare function get<Req extends {}, Res extends {}>(options: GetRequestOptions): Promise<AptosResponse<Req, Res>>;
/**
* Retrieves data from the Aptos full node using the provided options.
*
* @param options - The options for the request to the Aptos full node.
* @param options.aptosConfig - Configuration settings specific to the Aptos client and full node.
* @param options.aptosConfig.clientConfig - The client configuration settings.
* @param options.aptosConfig.fullnodeConfig - The full node configuration settings.
* @param options.overrides - Additional overrides for the request.
* @param options.type - The type of API request being made.
*
* @returns A promise that resolves with the response from the Aptos full node.
*/
declare function getAptosFullNode<Req extends {}, Res extends {}>(options: GetAptosRequestOptions): Promise<AptosResponse<Req, Res>>;
/**
* Makes a GET request to the Aptos Pepper service to retrieve data.
*
* @param options - The options for the request.
* @param options.param1 - Description of param1.
* @param options.param2 - Description of param2.
* @returns AptosResponse - The response from the Aptos Pepper service.
*/
declare function getAptosPepperService<Req extends {}, Res extends {}>(options: GetAptosRequestOptions): Promise<AptosResponse<Req, Res>>;
declare function paginateWithCursor<Req extends Record<string, any>, Res extends Array<{}>>(options: GetAptosRequestOptions): Promise<Res>;
/**
* Options for making a POST request, including the API client configuration.
*/
type PostRequestOptions = {
/**
* The config for the API client
*/
aptosConfig: AptosConfig;
/**
* The type of API endpoint to call e.g. fullnode, indexer, etc
*/
type: AptosApiType;
/**
* The name of the API method
*/
originMethod: string;
/**
* The URL path to the API method
*/
path: string;
/**
* The content type of the request body
*/
contentType?: MimeType;
/**
* The accepted content type of the response of the API
*/
acceptType?: MimeType;
/**
* The query parameters for the request
*/
params?: Record<string, string | AnyNumber | boolean | undefined>;
/**
* The body of the request, should match the content type of the request
*/
body?: any;
/**
* Specific client overrides for this request to override aptosConfig
*/
overrides?: ClientConfig;
};
/**
* Options for posting a request to Aptos, excluding the type field.
*/
type PostAptosRequestOptions = Omit<PostRequestOptions, "type">;
/**
* Executes a POST request to the specified URL with the provided options.
*
* @param options - The options for the POST request.
* @param options.type - The type of the request.
* @param options.originMethod - The original method that initiated the request.
* @param options.path - The path for the request.
* @param options.body - The body content to be sent with the request.
* @param options.acceptType - The type of response expected from the server.
* @param options.contentType - The content type of the request body.
* @param options.params - Additional parameters to include in the request.
* @param options.aptosConfig - Configuration settings for the Aptos request.
* @param options.overrides - Any overrides for the default request behavior.
* @returns The response from the POST request.
*/
declare function post<Req extends {}, Res extends {}>(options: PostRequestOptions): Promise<AptosResponse<Req, Res>>;
/**
* Sends a request to the Aptos full node using the specified options.
* This function allows you to interact with the Aptos blockchain by sending requests to the full node.
*
* @param options - The options for the request.
* @param options.aptosConfig - Configuration settings for the Aptos client.
* @param options.aptosConfig.clientConfig - Client-specific configuration settings.
* @param options.aptosConfig.fullnodeConfig - Full node-specific configuration settings.
* @param options.overrides - Additional overrides for the request.
*/
declare function postAptosFullNode<Req extends {}, Res extends {}>(options: PostAptosRequestOptions): Promise<AptosResponse<Req, Res>>;
/**
* Sends a request to the Aptos indexer with the specified options.
* This function allows you to interact with the Aptos indexer and customize the request using various configurations.
*
* @param options - The options for the request to the Aptos indexer.
* @param options.aptosConfig - Configuration settings specific to the Aptos client and indexer.
* @param options.aptosConfig.clientConfig - The client configuration settings.
* @param options.aptosConfig.indexerConfig - The indexer configuration settings.
* @param options.overrides - Additional overrides for the request.
* @param options.overrides.HEADERS - Custom headers to include in the request.
*/
declare function postAptosIndexer<Req extends {}, Res extends {}>(options: PostAptosRequestOptions): Promise<AptosResponse<Req, Res>>;
/**
* Sends a request to the Aptos faucet to obtain test tokens.
* This function modifies the provided configuration to ensure that the API_KEY is not included in the request.
*
* @param options - The options for the request.
* @param options.aptosConfig - The configuration settings for the Aptos client.
* @param options.aptosConfig.clientConfig - The client-specific configuration settings.
* @param options.aptosConfig.clientConfig.HEADERS - Optional headers to include in the request.
* @param options.aptosConfig.faucetConfig - The configuration settings specific to the faucet.
* @param options.overrides - Additional overrides for the request configuration.
*/
declare function postAptosFaucet<Req extends {}, Res extends {}>(options: PostAptosRequestOptions): Promise<AptosResponse<Req, Res>>;
/**
* Makes a post request to the pepper service.
*
* @param options - The options for the request.
* @param options.url - The URL to which the request is sent.
* @param options.headers - The headers to include in the request.
* @param options.body - The body of the request.
* @returns A promise that resolves to the response from the pepper service.
*/
declare function postAptosPepperService<Req extends {}, Res extends {}>(options: PostAptosRequestOptions): Promise<AptosResponse<Req, Res>>;
/**
* Sends a request to the Aptos proving service with the specified options.
*
* @param options - The options for the request to the Aptos proving service.
* @param options.type - The type of the request, which should be set to AptosApiType.PROVER.
* @param options.data - The data to be included in the request.
*/
declare function postAptosProvingService<Req extends {}, Res extends {}>(options: PostAptosRequestOptions): Promise<AptosResponse<Req, Res>>;
declare enum KeylessErrorCategory {
API_ERROR = 0,
EXTERNAL_API_ERROR = 1,
SESSION_EXPIRED = 2,
INVALID_STATE = 3,
UNKNOWN = 4
}
declare enum KeylessErrorResolutionTip {
REAUTHENTICATE = "Re-authentiate to continue using your keyless account",
REAUTHENTICATE_UNSURE = "Try re-authentiating. If the error persists join the telegram group at https://t.me/+h5CN-W35yUFiYzkx for further support",
UPDATE_REQUEST_PARAMS = "Update the invalid request parameters and reauthenticate.",
RATE_LIMIT_EXCEEDED = "Cache the keyless account and reuse it to avoid making too many requests. Keyless accounts are valid until either the EphemeralKeyPair expires, when the JWK is rotated, or when the proof verifying key is changed, whichever comes soonest.",
SERVER_ERROR = "Try again later. See aptosApiError error for more context. For additional support join the telegram group at https://t.me/+h5CN-W35yUFiYzkx",
CALL_PRECHECK = "Call `await account.checkKeylessAccountValidity()` to wait for asyncronous changes and check for account validity before signing or serializing.",
REINSTANTIATE = "Try instantiating the account again. Avoid manipulating the account object directly",
JOIN_SUPPORT_GROUP = "For support join the telegram group at https://t.me/+h5CN-W35yUFiYzkx",
UNKNOWN = "Error unknown. For support join the telegram group at https://t.me/+h5CN-W35yUFiYzkx"
}
declare enum KeylessErrorType {
EPHEMERAL_KEY_PAIR_EXPIRED = 0,
PROOF_NOT_FOUND = 1,
ASYNC_PROOF_FETCH_FAILED = 2,
INVALID_PROOF_VERIFICATION_FAILED = 3,
INVALID_PROOF_VERIFICATION_KEY_NOT_FOUND = 4,
INVALID_JWT_SIG = 5,
INVALID_JWT_JWK_NOT_FOUND = 6,
INVALID_JWT_ISS_NOT_RECOGNIZED = 7,
INVALID_JWT_FEDERATED_ISS_NOT_SUPPORTED = 8,
INVALID_TW_SIG_VERIFICATION_FAILED = 9,
INVALID_TW_SIG_PUBLIC_KEY_NOT_FOUND = 10,
INVALID_EXPIRY_HORIZON = 11,
JWT_PARSING_ERROR = 12,
JWK_FETCH_FAILED = 13,
JWK_FETCH_FAILED_FEDERATED = 14,
RATE_LIMIT_EXCEEDED = 15,
PEPPER_SERVICE_INTERNAL_ERROR = 16,
PEPPER_SERVICE_BAD_REQUEST = 17,
PEPPER_SERVICE_OTHER = 18,
PROVER_SERVICE_INTERNAL_ERROR = 19,
PROVER_SERVICE_BAD_REQUEST = 20,
PROVER_SERVICE_OTHER = 21,
FULL_NODE_CONFIG_LOOKUP_ERROR = 22,
FULL_NODE_VERIFICATION_KEY_LOOKUP_ERROR = 23,
FULL_NODE_JWKS_LOOKUP_ERROR = 24,
FULL_NODE_OTHER = 25,
UNKNOWN = 26
}
declare class KeylessError extends Error {
readonly innerError?: unknown;
readonly category: KeylessErrorCategory;
readonly resolutionTip: KeylessErrorResolutionTip;
readonly type: KeylessErrorType;
readonly details?: string;
/** @internal this constructor is for sdk internal use - do not instantiate outside of the SDK codebase */
constructor(args: {
innerError?: unknown;
category: KeylessErrorCategory;
resolutionTip: KeylessErrorResolutionTip;
type: KeylessErrorType;
message?: string;
details?: string;
});
static constructMessage(message: string, tip: KeylessErrorResolutionTip, innerError?: unknown, details?: string): string;
/**
* Static constructor that creates a KeylessError instance using the KeylessErrors constant
* @param args.type The type of KeylessError
* @param args.aptosApiError optional AptosApiError supplied for api errors
* @param args.details optional details to include in the error message
* @returns A new KeylessError instance
*/
static fromErrorType(args: {
type: KeylessErrorType;
error?: unknown;
details?: string;
}): KeylessError;
}
/**
* Options for handling errors in the Aptos API.
*/
type AptosApiErrorOpts = {
apiType: AptosApiType;
aptosRequest: AptosRequest;
aptosResponse: AptosResponse<any, any>;
};
/**
* Represents an error returned from the Aptos API.
* This class encapsulates the details of the error, including the request URL, response status, and additional data.
*
* @param name - The name of the error, which is always "AptosApiError".
* @param url - The URL to which the request was made.
* @param status - The HTTP response status code (e.g., 400).
* @param statusText - The message associated with the response status.
* @param data - The response data returned from the API.
* @param request - The original AptosRequest that triggered the error.
*/
declare class AptosApiError extends Error {
readonly url: string;
readonly status: number;
readonly statusText: string;
readonly data: any;
readonly request: AptosRequest;
/**
* Constructs an instance of AptosApiError with relevant error details.
*
* @param opts - The options for creating the AptosApiError.
* @param opts.apiType - The type of API that generated the error.
* @param opts.aptosRequest - The request object that caused the error.
* @param opts.aptosResponse - The response object containing error details.
*
* @internal This constructor is for SDK internal use - do not instantiate outside the SDK codebase.
*/
constructor({ apiType, aptosRequest, aptosResponse }: AptosApiErrorOpts);
}
export { APTOS_BIP44_REGEX, APTOS_COIN, APTOS_FA, APTOS_HARDENED_REGEX, AbstractKeylessAccount, Account$1 as Account, AccountAddress, AccountAddressInput, AccountAuthenticator, AccountAuthenticatorEd25519, AccountAuthenticatorMultiEd25519, AccountAuthenticatorMultiKey, AccountAuthenticatorNoAccountAuthenticator, AccountAuthenticatorSingleKey, AccountData, AccountPublicKey, AccountSequenceNumber, AnyNumber, AnyPublicKey, AnyPublicKeyVariant, type AnyRawTransaction, type AnyRawTransactionInstance, AnySignature, type AnyTransactionPayloadInstance, Aptos, AptosApiError, AptosApiType, AptosConfig, AptosRequest, AptosResponse, AptosSettings, AuthenticationKey, AuthenticationKeyScheme, Block, Bool, CKDPriv, ChainId, Client, ClientConfig, ClientRequest, ClientResponse, CommittedTransactionResponse, type CreateAccountFromPrivateKeyArgs, type CreateEd25519AccountFromPrivateKeyArgs, type CreateEd25519SingleKeyAccountFromPrivateKeyArgs, type CreateSingleKeyAccountFromPrivateKeyArgs, DEFAULT_MAX_GAS_AMOUNT, DEFAULT_TXN_EXP_SEC_FROM_NOW, DEFAULT_TXN_TIMEOUT_SEC, type DerivedKeys, Deserializable, type DeserializableClass, Deserializer, EPK_HORIZON_SECS, Ed25519Account, Ed25519PrivateKey, Ed25519PublicKey, Ed25519Signature, type Ed25519SignerConstructorArgs, type Ed25519SignerFromDerivationPathArgs, EntryFunction, type EntryFunctionABI, EntryFunctionArgument, type EntryFunctionArgumentTypes, EntryFunctionBytes, EphemeralCertificate, EphemeralCertificateVariant, EphemeralKeyPair, EphemeralPublicKey, EphemeralPublicKeyVariant, EphemeralSignature, type ExecutionFinishEventData, FIREBASE_AUTH_ISS_PATTERN, type FailureEventData, FaucetConfig, FederatedKeylessAccount, FederatedKeylessPublicKey, FeePayerRawTransaction, FixedBytes, FullNodeConfig, type FunctionABI, GasEstimation, type GenerateAccountArgs, type GenerateEd25519AccountArgs, type GenerateEd25519SingleKeyAccountArgs, type GenerateSingleKeyAccountArgs, GetANSNameResponse, GetAccountCoinsDataResponse, GetAccountCollectionsWithOwnedTokenResponse, GetAccountOwnedTokensFromCollectionResponse, GetAccountOwnedTokensQueryResponse, type GetAptosRequestOptions, GetChainTopUserTransactionsResponse, GetCollectionDataResponse, GetCurrentFungibleAssetBalancesResponse, GetCurrentTokenOwnershipResponse, GetDelegatedStakingActivitiesResponse, GetEventsResponse, GetFungibleAssetActivitiesResponse, GetFungibleAssetMetadataResponse, GetNumberOfDelegatorsResponse, GetObjectDataQueryResponse, GetOwnedTokensResponse, GetProcessorStatusResponse, type GetRequestOptions, GetTableItemsDataResponse, GetTableItemsMetadataResponse, GetTokenActivityResponse, GetTokenDataResponse, GraphqlQuery, Groth16VerificationKey, Groth16Zkp, HARDENED_OFFSET, Hex, HexInput, Identifier, IndexerConfig, type InputEntryFunctionData, type InputEntryFunctionDataWithABI, type InputEntryFunctionDataWithRemoteABI, type InputGenerateMultiAgentRawTransactionArgs, type InputGenerateMultiAgentRawTransactionData, type InputGenerateRawTransactionArgs, type InputGenerateSingleSignerRawTransactionArgs, type InputGenerateSingleSignerRawTransactionData, type InputGenerateTransactionData, type InputGenerateTransactionOptions, type InputGenerateTransactionPayloadData, type InputGenerateTransactionPayloadDataWithABI, type InputGenerateTransactionPayloadDataWithRemoteABI, type InputMultiSigData, type InputMultiSigDataWithABI, type InputMultiSigDataWithRemoteABI, type InputScriptData, type InputSimulateTransactionData, type InputSimulateTransactionOptions, type InputSubmitTransactionData, type InputViewFunctionData, type InputViewFunctionDataWithABI, type InputViewFunctionDataWithRemoteABI, type InputViewFunctionJsonData, KeyType, KeylessAccount, KeylessConfiguration, KeylessError, KeylessErrorCategory, KeylessErrorResolutionTip, KeylessErrorType, KeylessPublicKey, KeylessSignature, type KeylessSigner, LedgerInfo, LedgerVersionArg, MAX_AUD_VAL_BYTES, MAX_COMMITED_EPK_BYTES, MAX_EXTRA_FIELD_BYTES, MAX_ISS_VAL_BYTES, MAX_JWT_HEADER_B64_BYTES, MAX_UID_KEY_BYTES, MAX_UID_VAL_BYTES, MimeType, ModuleId, MoveFunction, MoveFunctionGenericTypeParam, MoveFunctionId, MoveJWK, MoveModuleBytecode, MoveModuleId, MoveOption, MoveResource, MoveString, MoveStructId, MoveValue, MoveVector, MultiAgentRawTransaction, MultiAgentTransaction, MultiEd25519PublicKey, MultiEd25519Signature, MultiKey, MultiKeyAccount, MultiKeySignature, MultiSig, MultiSigTransactionPayload, Network, OrderByArg, PaginationArgs, PendingTransactionResponse, type PostAptosRequestOptions, type PostRequestOptions, PrivateKey, type PrivateKeyFromDerivationPathArgs, PrivateKeyVariants, ProcessorType, type ProofFetchCallback, type ProofFetchEvents, type ProofFetchFailure, type ProofFetchStatus, type ProofFetchSuccess, PublicKey, RAW_TRANSACTION_SALT, RAW_TRANSACTION_WITH_DATA_SALT, RawTransaction, RawTransactionWithData, RotationProofChallenge, Script, ScriptFunctionArgument, type ScriptFunctionArgumentTypes, Secp256k1PrivateKey, Secp256k1PublicKey, Secp256k1Signature, Serializable, Serialized, Serializer, Signature, SignedTransaction, SigningScheme, SigningSchemeInput, type SimpleEntryFunctionArgumentTypes, SimpleTransaction, SingleKeyAccount, type SingleKeySignerConstructorArgs, type SingleKeySignerFromDerivationPathArgs, type SingleKeySignerGenerateArgs, StructTag, type SuccessEventData, TableItemRequest, TokenStandardArg, TransactionAndProof, TransactionArgument, TransactionAuthenticator, TransactionAuthenticatorEd25519, TransactionAuthenticatorFeePayer, TransactionAuthenticatorMultiAgent, TransactionAuthenticatorMultiEd25519, TransactionAuthenticatorSingleSender, TransactionPayload, TransactionPayloadEntryFunction, TransactionPayloadMultiSig, TransactionPayloadScript, TransactionResponse, TransactionWorker, type TransactionWorkerEvents, TransactionWorkerEventsEnum, type TypeArgument, TypeTag, TypeTagAddress, TypeTagBool, TypeTagGeneric, TypeTagParserError, TypeTagParserErrorType, TypeTagReference, TypeTagSigner, TypeTagStruct, TypeTagU128, TypeTagU16, TypeTagU256, TypeTagU32, TypeTagU64, TypeTagU8, TypeTagVector, U128, U16, U256, U32, U64, U8, Uint16, Uint32, Uint8, UserTransactionResponse, type VerifyEd25519SignatureArgs, type VerifyMultiKeySignatureArgs, type VerifySignatureArgs, type VerifySingleKeySignatureArgs, type ViewFunctionABI, type ViewFunctionJsonPayload, WaitForTransactionOptions, WhereArg, ZeroKnowledgeSig, ZkProof, ZkpVariant, aptosCoinStructTag, aptosRequest, base64UrlDecode, bigIntToBytesLE, buildTransaction, bytesToBigIntLE, checkOrConvertArgument, convertAmountFromHumanReadableToOnChain, convertAmountFromOnChainToHumanReadable, convertArgument, convertNumber, createObjectAddress, createResourceAddress, createTokenAddress, deriveKey, deriveTransactionType, deserializeFromScriptArgument, fetchEntryFunctionAbi, fetchFunctionAbi, fetchViewFunctionAbi, findFirstNonSignerArg, floorToWholeHour, generateRawTransaction, generateSignedTransaction, generateSignedTransactionForSimulation, generateSigningMessage, generateSigningMessageForSerializable, generateSigningMessageForTransaction, generateTransactionPayload, generateTransactionPayloadWithABI, generateUserTransactionHash, generateViewFunctionPayload, generateViewFunctionPayloadWithABI, get, getAptosFullNode, getAptosPepperService, getAuthenticatorForSimulation, getErrorMessage, getFunctionParts, getIssAudAndUidVal, getKeylessConfig, getKeylessJWKs, hashStrToField, hashValues, isBcsAddress, isBcsBool, isBcsFixedBytes, isBcsString, isBcsU128, isBcsU16, isBcsU256, isBcsU32, isBcsU64, isBcsU8, isBool, isCanonicalEd25519Signature, isEmptyOption, isEncodedEntryFunctionArgument, isEncodedStruct, isKeylessSigner, isLargeNumber, isNumber, isScriptDataInput, isString, isValidBIP44Path, isValidHardenedPath, mnemonicToSeed, normalizeBundle, nowInSeconds, objectStructTag, optionStructTag, padAndPackBytesWithLen, paginateWithCursor, parseEncodedStruct, parseJwtHeader, parseTypeTag, poseidonHash, post, postAptosFaucet, postAptosFullNode, postAptosIndexer, postAptosPepperService, postAptosProvingService, promiseFulfilledStatus, request, sleep, splitPath, standardizeTypeTags, stringStructTag, throwTypeMismatch };
Выполнить команду
Для локальной разработки. Не используйте в интернете!