Comparing version 1.0.0 to 1.1.0
@@ -364,3 +364,3 @@ export interface AptosError { | ||
name: string; | ||
visibility: "public" | "script" | "friend"; | ||
visibility: 'public' | 'script' | 'friend'; | ||
generic_type_params: { | ||
@@ -898,3 +898,2 @@ constraints: MoveAbility[]; | ||
type: string; | ||
/** all public keys of the sender account */ | ||
public_keys: HexEncodedBytes[]; | ||
@@ -1061,2 +1060,28 @@ /** signatures created based on the `threshold` */ | ||
} | ||
export interface TokenData { | ||
/** Unique name within this creator's account for this Token's collection */ | ||
collection: string; | ||
/** Description of Token */ | ||
description: string; | ||
/** Name of Token */ | ||
name: string; | ||
/** Optional maximum number of this Token */ | ||
maximum?: number; | ||
/** Total number of this type of Token */ | ||
supply: number; | ||
/** URL for additional information / media */ | ||
uri: string; | ||
} | ||
export interface TokenId { | ||
/** Token creator address */ | ||
creator: string; | ||
/** Unique name within this creator's account for this Token's collection */ | ||
collection: string; | ||
/** Name of Token */ | ||
name: string; | ||
} | ||
export interface Token { | ||
id: TokenId; | ||
value: number; | ||
} | ||
//# sourceMappingURL=data-contracts.d.ts.map |
@@ -10,20 +10,72 @@ import * as Nacl from 'tweetnacl'; | ||
} | ||
/** | ||
* Class for creating and managing Aptos account | ||
*/ | ||
export declare class AptosAccount { | ||
/** | ||
* A private key and public key, associated with the given account | ||
*/ | ||
readonly signingKey: Nacl.SignKeyPair; | ||
/** | ||
* Address associated with the given account | ||
*/ | ||
private readonly accountAddress; | ||
private authKeyCached?; | ||
static fromAptosAccountObject(obj: AptosAccountObject): AptosAccount; | ||
/** This class allows passing in an address, to handle account key rotation, where auth_key != public_key */ | ||
/** | ||
* Creates new account instance. Constructor allows passing in an address, | ||
* to handle account key rotation, where auth_key != public_key | ||
* @param privateKeyBytes Private key from which account key pair will be generated. | ||
* If not specified, new key pair is going to be created. | ||
* @param address Account address (e.g. 0xe8012714cd17606cee7188a2a365eef3fe760be598750678c8c5954eb548a591). | ||
* If not specified, a new one will be generated from public key | ||
*/ | ||
constructor(privateKeyBytes?: Uint8Array | undefined, address?: MaybeHexString); | ||
/** Returns the address associated with the given account */ | ||
/** | ||
* This is the key by which Aptos account is referenced. | ||
* It is the 32-byte of the SHA-3 256 cryptographic hash | ||
* of the public key(s) concatenated with a signature scheme identifier byte | ||
* @returns Address associated with the given account | ||
*/ | ||
address(): HexString; | ||
/** Returns the authKey for the associated account | ||
* See here for more info: https://aptos.dev/basics/basics-accounts#single-signer-authentication */ | ||
/** | ||
* 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/basics/basics-accounts#single-signer-authentication} | ||
* @returns Authentication key for the associated account | ||
*/ | ||
authKey(): HexString; | ||
/** Returns the public key for the associated account */ | ||
/** | ||
* This key is generated with Ed25519 scheme. | ||
* Public key is used to check a signature of transaction, signed by given account | ||
* @returns The public key for the associated account | ||
*/ | ||
pubKey(): HexString; | ||
/** | ||
* Signs specified `buffer` with account's private key | ||
* @param buffer A buffer to sign | ||
* @returns A signature HexString | ||
*/ | ||
signBuffer(buffer: Buffer): HexString; | ||
/** | ||
* Signs specified `hexString` with account's private key | ||
* @param hexString A regular string or HexString to sign | ||
* @returns A signature HexString | ||
*/ | ||
signHexString(hexString: MaybeHexString): HexString; | ||
/** | ||
* Derives account address, public key and private key | ||
* @returns AptosAccountObject instance. | ||
* @example An example of the returned AptosAccountObject object | ||
* ``` | ||
* { | ||
* address: "0xe8012714cd17606cee7188a2a365eef3fe760be598750678c8c5954eb548a591", | ||
* publicKeyHex: "0xf56d8524faf79fbc0f48c13aeed3b0ce5dd376b4db93b8130a107c0a5e04ba04", | ||
* privateKeyHex: `0x009c9f7c992a06cfafe916f125d8adb7a395fca243e264a8e56a4b3e6accf940 | ||
* d2b11e9ece3049ce60e3c7b4a1c58aebfa9298e29a30a58a67f1998646135204` | ||
* } | ||
* ``` | ||
*/ | ||
toPrivateKeyObject(): AptosAccountObject; | ||
} | ||
//# sourceMappingURL=aptos_account.d.ts.map |
@@ -31,4 +31,14 @@ "use strict"; | ||
const hex_string_1 = require("./hex_string"); | ||
/** | ||
* Class for creating and managing Aptos account | ||
*/ | ||
class AptosAccount { | ||
/** This class allows passing in an address, to handle account key rotation, where auth_key != public_key */ | ||
/** | ||
* Creates new account instance. Constructor allows passing in an address, | ||
* to handle account key rotation, where auth_key != public_key | ||
* @param privateKeyBytes Private key from which account key pair will be generated. | ||
* If not specified, new key pair is going to be created. | ||
* @param address Account address (e.g. 0xe8012714cd17606cee7188a2a365eef3fe760be598750678c8c5954eb548a591). | ||
* If not specified, a new one will be generated from public key | ||
*/ | ||
constructor(privateKeyBytes, address) { | ||
@@ -46,8 +56,17 @@ if (privateKeyBytes) { | ||
} | ||
/** Returns the address associated with the given account */ | ||
/** | ||
* This is the key by which Aptos account is referenced. | ||
* It is the 32-byte of the SHA-3 256 cryptographic hash | ||
* of the public key(s) concatenated with a signature scheme identifier byte | ||
* @returns Address associated with the given account | ||
*/ | ||
address() { | ||
return this.accountAddress; | ||
} | ||
/** Returns the authKey for the associated account | ||
* See here for more info: https://aptos.dev/basics/basics-accounts#single-signer-authentication */ | ||
/** | ||
* 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/basics/basics-accounts#single-signer-authentication} | ||
* @returns Authentication key for the associated account | ||
*/ | ||
authKey() { | ||
@@ -62,6 +81,15 @@ if (!this.authKeyCached) { | ||
} | ||
/** Returns the public key for the associated account */ | ||
/** | ||
* This key is generated with Ed25519 scheme. | ||
* Public key is used to check a signature of transaction, signed by given account | ||
* @returns The public key for the associated account | ||
*/ | ||
pubKey() { | ||
return hex_string_1.HexString.ensure(buffer_1.Buffer.from(this.signingKey.publicKey).toString('hex')); | ||
} | ||
/** | ||
* Signs specified `buffer` with account's private key | ||
* @param buffer A buffer to sign | ||
* @returns A signature HexString | ||
*/ | ||
signBuffer(buffer) { | ||
@@ -71,2 +99,7 @@ const signature = Nacl.sign(buffer, this.signingKey.secretKey); | ||
} | ||
/** | ||
* Signs specified `hexString` with account's private key | ||
* @param hexString A regular string or HexString to sign | ||
* @returns A signature HexString | ||
*/ | ||
signHexString(hexString) { | ||
@@ -76,2 +109,15 @@ const toSign = hex_string_1.HexString.ensure(hexString).toBuffer(); | ||
} | ||
/** | ||
* Derives account address, public key and private key | ||
* @returns AptosAccountObject instance. | ||
* @example An example of the returned AptosAccountObject object | ||
* ``` | ||
* { | ||
* address: "0xe8012714cd17606cee7188a2a365eef3fe760be598750678c8c5954eb548a591", | ||
* publicKeyHex: "0xf56d8524faf79fbc0f48c13aeed3b0ce5dd376b4db93b8130a107c0a5e04ba04", | ||
* privateKeyHex: `0x009c9f7c992a06cfafe916f125d8adb7a395fca243e264a8e56a4b3e6accf940 | ||
* d2b11e9ece3049ce60e3c7b4a1c58aebfa9298e29a30a58a67f1998646135204` | ||
* } | ||
* ``` | ||
*/ | ||
toPrivateKeyObject() { | ||
@@ -78,0 +124,0 @@ return { |
@@ -10,3 +10,3 @@ import { AxiosRequestConfig, AxiosResponse } from 'axios'; | ||
import { Tables } from './api/Tables'; | ||
import * as TxnBuilderTypes from './transaction_builder/aptos_types'; | ||
import { TxnBuilderTypes } from './transaction_builder'; | ||
export declare class RequestError extends Error { | ||
@@ -19,2 +19,6 @@ response?: AxiosResponse<any, Types.AptosError>; | ||
export declare function raiseForStatus<T>(expectedStatus: number, response: AxiosResponse<T, Types.AptosError>, requestContent?: any): void; | ||
/** | ||
* Provides methods for retrieving data from Aptos node. | ||
* For more detailed API specification see {@link https://fullnode.devnet.aptoslabs.com/spec.html#/} | ||
*/ | ||
export declare class AptosClient { | ||
@@ -27,6 +31,30 @@ nodeUrl: string; | ||
transactions: Transactions; | ||
/** | ||
* Establishes a connection to Aptos node | ||
* @param nodeUrl A url of the Aptos Node API endpoint | ||
* @param config An optional config for inner axios instance. | ||
* Detailed `config` description: {@link https://github.com/axios/axios#request-config} | ||
*/ | ||
constructor(nodeUrl: string, config?: AptosClientConfig); | ||
/** Returns the sequence number and authentication key for an account */ | ||
/** | ||
* Queries an Aptos account by address | ||
* @param accountAddress Hex-encoded 16 bytes Aptos account address | ||
* @returns Core account resource, used for identifying account and transaction execution | ||
* @example An example of the returned account | ||
* ``` | ||
* { | ||
* sequence_number: "1", | ||
* authentication_key: "0x5307b5f4bc67829097a8ba9b43dba3b88261eeccd1f709d9bde240fc100fbb69" | ||
* } | ||
* ``` | ||
*/ | ||
getAccount(accountAddress: MaybeHexString): Promise<Types.Account>; | ||
/** Returns transactions sent by the account */ | ||
/** | ||
* Queries transactions sent by given account | ||
* @param accountAddress Hex-encoded 16 bytes Aptos account address | ||
* @param query Optional pagination object | ||
* @param query.start The start transaction version of the page. Default is the latest ledger version | ||
* @param query.limit The max number of transactions should be returned for the page. Default is 25. | ||
* @returns An array of on-chain transactions, sent by account | ||
*/ | ||
getAccountTransactions(accountAddress: MaybeHexString, query?: { | ||
@@ -36,15 +64,55 @@ start?: number; | ||
}): Promise<Types.OnChainTransaction[]>; | ||
/** Returns all modules associated with the account */ | ||
/** | ||
* Queries modules associated with given account | ||
* @param accountAddress Hex-encoded 16 bytes Aptos account address | ||
* @param query.version Specifies ledger version of transactions. By default latest version will be used | ||
* @returns Account modules array for a specific ledger version. | ||
* Module is represented by MoveModule interface. It contains module `bytecode` and `abi`, | ||
* which is JSON representation of a module | ||
*/ | ||
getAccountModules(accountAddress: MaybeHexString, query?: { | ||
version?: Types.LedgerVersion; | ||
}): Promise<Types.MoveModule[]>; | ||
/** Returns the module identified by address and module name */ | ||
/** | ||
* Queries module associated with given account by module name | ||
* @param accountAddress Hex-encoded 16 bytes Aptos account address | ||
* @param moduleName The name of the module | ||
* @param query.version Specifies ledger version of transactions. By default latest version will be used | ||
* @returns Specified module. | ||
* Module is represented by MoveModule interface. It contains module `bytecode` and `abi`, | ||
* which JSON representation of a module | ||
*/ | ||
getAccountModule(accountAddress: MaybeHexString, moduleName: string, query?: { | ||
version?: Types.LedgerVersion; | ||
}): Promise<Types.MoveModule>; | ||
/** Returns all resources associated with the account */ | ||
/** | ||
* Queries all resources associated with given account | ||
* @param accountAddress Hex-encoded 16 bytes Aptos account address | ||
* @param query.version Specifies ledger version of transactions. By default latest version will be used | ||
* @returns Account resources for a specific ledger version | ||
* @example An example of an account resource | ||
* ``` | ||
* { | ||
* type: "0x1::AptosAccount::Coin", | ||
* data: { value: 6 } | ||
* } | ||
* ``` | ||
*/ | ||
getAccountResources(accountAddress: MaybeHexString, query?: { | ||
version?: Types.LedgerVersion; | ||
}): Promise<Types.AccountResource[]>; | ||
/** Returns the resource by the address and resource type */ | ||
/** | ||
* Queries resource associated with given account by resource type | ||
* @param accountAddress Hex-encoded 16 bytes Aptos account address | ||
* @param resourceType String representation of an on-chain Move struct type | ||
* @param query.version Specifies ledger version of transactions. By default latest version will be used | ||
* @returns Account resource of specified type and ledger version | ||
* @example An example of an account resource | ||
* ``` | ||
* { | ||
* type: "0x1::AptosAccount::Coin", | ||
* data: { value: 6 } | ||
* } | ||
* ``` | ||
*/ | ||
getAccountResource(accountAddress: MaybeHexString, resourceType: string, query?: { | ||
@@ -54,14 +122,58 @@ version?: Types.LedgerVersion; | ||
/** Generates a signed transaction that can be submitted to the chain for execution. */ | ||
static generateBCSTransaction(accountFrom: AptosAccount, rawTxn: TxnBuilderTypes.RawTransaction): Promise<Uint8Array>; | ||
static generateBCSTransaction(accountFrom: AptosAccount, rawTxn: TxnBuilderTypes.RawTransaction): Uint8Array; | ||
/** Generates a transaction request that can be submitted to produce a raw transaction that | ||
* can be signed, which upon being signed can be submitted to the blockchain. */ | ||
* can be signed, which upon being signed can be submitted to the blockchain | ||
* @param sender Hex-encoded 16 bytes Aptos account address of transaction sender | ||
* @param payload Transaction payload. It depends on transaction type you want to send | ||
* @param options Options allow to overwrite default transaction options. | ||
* Defaults are: | ||
* ```bash | ||
* { | ||
* sender: senderAddress.hex(), | ||
* sequence_number: account.sequence_number, | ||
* max_gas_amount: "1000", | ||
* gas_unit_price: "1", | ||
* gas_currency_code: "XUS", | ||
* // Unix timestamp, in seconds + 10 seconds | ||
* expiration_timestamp_secs: (Math.floor(Date.now() / 1000) + 10).toString(), | ||
* } | ||
* ``` | ||
* @returns A transaction object | ||
*/ | ||
generateTransaction(sender: MaybeHexString, payload: Types.TransactionPayload, options?: Partial<Types.UserTransactionRequest>): Promise<Types.UserTransactionRequest>; | ||
/** Converts a transaction request by `generate_transaction` into it's binary hex BCS representation, ready for | ||
/** | ||
* Converts a transaction request by `generate_transaction` into it's binary hex BCS representation, ready for | ||
* signing and submitting. | ||
* Generally you may want to use `signTransaction`, as it takes care of this step + signing */ | ||
* Generally you may want to use `signTransaction`, as it takes care of this step + signing | ||
* @param txnRequest A raw transaction generated by `generateTransaction` method | ||
* @returns A hex-encoded string prefixed with `0x` and fulfilled with two hex digits per byte | ||
*/ | ||
createSigningMessage(txnRequest: Types.UserTransactionRequest): Promise<Types.HexEncodedBytes>; | ||
/** Converts a transaction request produced by `generate_transaction` into a properly signed | ||
* transaction, which can then be submitted to the blockchain. */ | ||
* transaction, which can then be submitted to the blockchain | ||
* @param accountFrom AptosAccount of transaction sender | ||
* @param txnRequest A raw transaction generated by `generateTransaction` method | ||
* @returns A transaction, signed with sender account | ||
*/ | ||
signTransaction(accountFrom: AptosAccount, txnRequest: Types.UserTransactionRequest): Promise<Types.SubmitTransactionRequest>; | ||
/** | ||
* Queries events by event key | ||
* @param eventKey Event key for an event stream. It is BCS serialized bytes | ||
* of `guid` field in the Move struct `EventHandle` | ||
* @returns Array of events assotiated with given key | ||
*/ | ||
getEventsByEventKey(eventKey: Types.HexEncodedBytes): Promise<Types.Event[]>; | ||
/** | ||
* Extracts event key from the account resource identified by the | ||
* `event_handle_struct` and `field_name`, then returns events identified by the event key | ||
* @param address Hex-encoded 16 bytes Aptos account from which events are queried | ||
* @param eventHandleStruct String representation of an on-chain Move struct type. | ||
* (e.g. `0x1::Coin::CoinStore<0x1::TestCoin::TestCoin>`) | ||
* @param fieldName The field name of the EventHandle in the struct | ||
* @param query Optional query object | ||
* @param query.start The start sequence number in the EVENT STREAM, defaulting to the latest event. | ||
* The events are returned in the reverse order of sequence number | ||
* @param query.limit The number of events to be returned for the page default is 5 | ||
* @returns Array of events | ||
*/ | ||
getEventsByEventHandle(address: MaybeHexString, eventHandleStruct: Types.MoveStructTagId, fieldName: string, query?: { | ||
@@ -71,6 +183,21 @@ start?: number; | ||
}): Promise<Types.Event[]>; | ||
/** Submits a signed transaction to the transaction endpoint that takes JSON payload. */ | ||
/** | ||
* Submits a signed transaction to the transaction endpoint that takes JSON payload | ||
* @param signedTxnRequest A transaction, signed by `signTransaction` method | ||
* @returns Transaction that is accepted and submitted to mempool | ||
*/ | ||
submitTransaction(signedTxnRequest: Types.SubmitTransactionRequest): Promise<Types.PendingTransaction>; | ||
/** Submits a signed transaction to the the endpoint that takes BCS payload. */ | ||
/** | ||
* Submits a signed transaction to the the endpoint that takes BCS payload | ||
* @param signedTxn A BCS transaction representation | ||
* @returns Transaction that is accepted and submitted to mempool | ||
*/ | ||
submitSignedBCSTransaction(signedTxn: Uint8Array): Promise<Types.PendingTransaction>; | ||
/** | ||
* Queries on-chain transactions | ||
* @param query Optional pagination object | ||
* @param query.start The start transaction version of the page. Default is the latest ledger version | ||
* @param query.limit The max number of transactions should be returned for the page. Default is 25 | ||
* @returns Array of on-chain transactions | ||
*/ | ||
getTransactions(query?: { | ||
@@ -80,10 +207,72 @@ start?: number; | ||
}): Promise<Types.OnChainTransaction[]>; | ||
/** | ||
* Queries transaction by hash or version. When given transaction hash, server first looks up | ||
* on-chain transaction by hash; if no on-chain transaction found, then look up transaction | ||
* by hash in the mempool (pending) transactions. | ||
* When given a transaction version, server looks up the transaction on-chain by version | ||
* @param txnHashOrVersion - Transaction hash should be hex-encoded bytes string with 0x prefix. | ||
* Transaction version is an uint64 number. | ||
* @returns Transaction from mempool or on-chain transaction | ||
*/ | ||
getTransaction(txnHashOrVersion: string): Promise<Types.Transaction>; | ||
/** | ||
* Defines if specified transaction is currently in pending state | ||
* @param txnHash A hash of transaction | ||
* | ||
* To create a transaction hash: | ||
* | ||
* 1. Create hash message bytes: "Aptos::Transaction" bytes + BCS bytes of Transaction. | ||
* 2. Apply hash algorithm SHA3-256 to the hash message bytes. | ||
* 3. Hex-encode the hash bytes with 0x prefix. | ||
* | ||
* @returns `true` if transaction is in pending state and `false` otherwise | ||
*/ | ||
transactionPending(txnHash: Types.HexEncodedBytes): Promise<boolean>; | ||
/** Waits up to 10 seconds for a transaction to move past pending state */ | ||
/** | ||
* Waits up to 10 seconds for a transaction to move past pending state | ||
* @param txnHash A hash of transaction | ||
* @returns A Promise, that will resolve if transaction is accepted to the blockchain, | ||
* and reject if more then 10 seconds passed | ||
* @example | ||
* ``` | ||
* const signedTxn = await this.aptosClient.signTransaction(account, txnRequest); | ||
* const res = await this.aptosClient.submitTransaction(signedTxn); | ||
* await this.aptosClient.waitForTransaction(res.hash); | ||
* // do smth after transaction is accepted into blockchain | ||
* ``` | ||
*/ | ||
waitForTransaction(txnHash: Types.HexEncodedBytes): Promise<void>; | ||
/** | ||
* Queries the latest ledger information | ||
* @param params Request params | ||
* @returns Latest ledger information | ||
* @example Example of returned data | ||
* ``` | ||
* { | ||
* chain_id: 15, | ||
* epoch: 6, | ||
* ledger_version: "2235883", | ||
* ledger_timestamp:"1654580922321826" | ||
* } | ||
* ``` | ||
*/ | ||
getLedgerInfo(params?: RequestParams): Promise<Types.LedgerInfo>; | ||
/** | ||
* @param params Request params | ||
* @returns Current chain id | ||
*/ | ||
getChainId(params?: RequestParams): Promise<number>; | ||
/** | ||
* Gets a table item for a table identified by the handle and the key for the item. | ||
* Key and value types need to be passed in to help with key serialization and value deserialization. | ||
* @param handle A pointer to where that table is stored | ||
* @param data Object, that describes table item | ||
* @param data.key_type Move type of table key (e.g. `vector<u8>`) | ||
* @param data.value_type Move type of table value (e.g. `u64`) | ||
* @param data.key Value of table key | ||
* @param params Request params | ||
* @returns Table item value rendered in JSON | ||
*/ | ||
getTableItem(handle: string, data: Types.TableItemRequest, params?: RequestParams): Promise<any>; | ||
} | ||
//# sourceMappingURL=aptos_client.d.ts.map |
@@ -32,3 +32,13 @@ "use strict"; | ||
exports.raiseForStatus = raiseForStatus; | ||
/** | ||
* Provides methods for retrieving data from Aptos node. | ||
* For more detailed API specification see {@link https://fullnode.devnet.aptoslabs.com/spec.html#/} | ||
*/ | ||
class AptosClient { | ||
/** | ||
* Establishes a connection to Aptos node | ||
* @param nodeUrl A url of the Aptos Node API endpoint | ||
* @param config An optional config for inner axios instance. | ||
* Detailed `config` description: {@link https://github.com/axios/axios#request-config} | ||
*/ | ||
constructor(nodeUrl, config) { | ||
@@ -49,3 +59,14 @@ this.nodeUrl = nodeUrl; | ||
} | ||
/** Returns the sequence number and authentication key for an account */ | ||
/** | ||
* Queries an Aptos account by address | ||
* @param accountAddress Hex-encoded 16 bytes Aptos account address | ||
* @returns Core account resource, used for identifying account and transaction execution | ||
* @example An example of the returned account | ||
* ``` | ||
* { | ||
* sequence_number: "1", | ||
* authentication_key: "0x5307b5f4bc67829097a8ba9b43dba3b88261eeccd1f709d9bde240fc100fbb69" | ||
* } | ||
* ``` | ||
*/ | ||
async getAccount(accountAddress) { | ||
@@ -56,3 +77,10 @@ const response = await this.accounts.getAccount(hex_string_1.HexString.ensure(accountAddress).hex()); | ||
} | ||
/** Returns transactions sent by the account */ | ||
/** | ||
* Queries transactions sent by given account | ||
* @param accountAddress Hex-encoded 16 bytes Aptos account address | ||
* @param query Optional pagination object | ||
* @param query.start The start transaction version of the page. Default is the latest ledger version | ||
* @param query.limit The max number of transactions should be returned for the page. Default is 25. | ||
* @returns An array of on-chain transactions, sent by account | ||
*/ | ||
async getAccountTransactions(accountAddress, query) { | ||
@@ -63,3 +91,10 @@ const response = await this.accounts.getAccountTransactions(hex_string_1.HexString.ensure(accountAddress).hex(), query); | ||
} | ||
/** Returns all modules associated with the account */ | ||
/** | ||
* Queries modules associated with given account | ||
* @param accountAddress Hex-encoded 16 bytes Aptos account address | ||
* @param query.version Specifies ledger version of transactions. By default latest version will be used | ||
* @returns Account modules array for a specific ledger version. | ||
* Module is represented by MoveModule interface. It contains module `bytecode` and `abi`, | ||
* which is JSON representation of a module | ||
*/ | ||
async getAccountModules(accountAddress, query) { | ||
@@ -70,3 +105,11 @@ const response = await this.accounts.getAccountModules(hex_string_1.HexString.ensure(accountAddress).hex(), query); | ||
} | ||
/** Returns the module identified by address and module name */ | ||
/** | ||
* Queries module associated with given account by module name | ||
* @param accountAddress Hex-encoded 16 bytes Aptos account address | ||
* @param moduleName The name of the module | ||
* @param query.version Specifies ledger version of transactions. By default latest version will be used | ||
* @returns Specified module. | ||
* Module is represented by MoveModule interface. It contains module `bytecode` and `abi`, | ||
* which JSON representation of a module | ||
*/ | ||
async getAccountModule(accountAddress, moduleName, query) { | ||
@@ -77,3 +120,15 @@ const response = await this.accounts.getAccountModule(hex_string_1.HexString.ensure(accountAddress).hex(), moduleName, query); | ||
} | ||
/** Returns all resources associated with the account */ | ||
/** | ||
* Queries all resources associated with given account | ||
* @param accountAddress Hex-encoded 16 bytes Aptos account address | ||
* @param query.version Specifies ledger version of transactions. By default latest version will be used | ||
* @returns Account resources for a specific ledger version | ||
* @example An example of an account resource | ||
* ``` | ||
* { | ||
* type: "0x1::AptosAccount::Coin", | ||
* data: { value: 6 } | ||
* } | ||
* ``` | ||
*/ | ||
async getAccountResources(accountAddress, query) { | ||
@@ -84,3 +139,16 @@ const response = await this.accounts.getAccountResources(hex_string_1.HexString.ensure(accountAddress).hex(), query); | ||
} | ||
/** Returns the resource by the address and resource type */ | ||
/** | ||
* Queries resource associated with given account by resource type | ||
* @param accountAddress Hex-encoded 16 bytes Aptos account address | ||
* @param resourceType String representation of an on-chain Move struct type | ||
* @param query.version Specifies ledger version of transactions. By default latest version will be used | ||
* @returns Account resource of specified type and ledger version | ||
* @example An example of an account resource | ||
* ``` | ||
* { | ||
* type: "0x1::AptosAccount::Coin", | ||
* data: { value: 6 } | ||
* } | ||
* ``` | ||
*/ | ||
async getAccountResource(accountAddress, resourceType, query) { | ||
@@ -92,13 +160,29 @@ const response = await this.accounts.getAccountResource(hex_string_1.HexString.ensure(accountAddress).hex(), resourceType, query); | ||
/** Generates a signed transaction that can be submitted to the chain for execution. */ | ||
static async generateBCSTransaction(accountFrom, rawTxn) { | ||
static generateBCSTransaction(accountFrom, rawTxn) { | ||
const txnBuilder = new transaction_builder_1.TransactionBuilderEd25519((signingMessage) => { | ||
// @ts-ignore | ||
const sigHexStr = accountFrom.signBuffer(signingMessage); | ||
return sigHexStr.toUint8Array(); | ||
return new transaction_builder_1.TxnBuilderTypes.Ed25519Signature(sigHexStr.toUint8Array()); | ||
}, accountFrom.pubKey().toUint8Array()); | ||
const signedTxn = await txnBuilder.sign(rawTxn); | ||
return signedTxn; | ||
return txnBuilder.sign(rawTxn); | ||
} | ||
/** Generates a transaction request that can be submitted to produce a raw transaction that | ||
* can be signed, which upon being signed can be submitted to the blockchain. */ | ||
* can be signed, which upon being signed can be submitted to the blockchain | ||
* @param sender Hex-encoded 16 bytes Aptos account address of transaction sender | ||
* @param payload Transaction payload. It depends on transaction type you want to send | ||
* @param options Options allow to overwrite default transaction options. | ||
* Defaults are: | ||
* ```bash | ||
* { | ||
* sender: senderAddress.hex(), | ||
* sequence_number: account.sequence_number, | ||
* max_gas_amount: "1000", | ||
* gas_unit_price: "1", | ||
* gas_currency_code: "XUS", | ||
* // Unix timestamp, in seconds + 10 seconds | ||
* expiration_timestamp_secs: (Math.floor(Date.now() / 1000) + 10).toString(), | ||
* } | ||
* ``` | ||
* @returns A transaction object | ||
*/ | ||
async generateTransaction(sender, payload, options) { | ||
@@ -119,5 +203,9 @@ const senderAddress = hex_string_1.HexString.ensure(sender); | ||
} | ||
/** Converts a transaction request by `generate_transaction` into it's binary hex BCS representation, ready for | ||
/** | ||
* Converts a transaction request by `generate_transaction` into it's binary hex BCS representation, ready for | ||
* signing and submitting. | ||
* Generally you may want to use `signTransaction`, as it takes care of this step + signing */ | ||
* Generally you may want to use `signTransaction`, as it takes care of this step + signing | ||
* @param txnRequest A raw transaction generated by `generateTransaction` method | ||
* @returns A hex-encoded string prefixed with `0x` and fulfilled with two hex digits per byte | ||
*/ | ||
async createSigningMessage(txnRequest) { | ||
@@ -130,3 +218,7 @@ const response = await this.transactions.createSigningMessage(txnRequest); | ||
/** Converts a transaction request produced by `generate_transaction` into a properly signed | ||
* transaction, which can then be submitted to the blockchain. */ | ||
* transaction, which can then be submitted to the blockchain | ||
* @param accountFrom AptosAccount of transaction sender | ||
* @param txnRequest A raw transaction generated by `generateTransaction` method | ||
* @returns A transaction, signed with sender account | ||
*/ | ||
async signTransaction(accountFrom, txnRequest) { | ||
@@ -142,2 +234,8 @@ const message = await this.createSigningMessage(txnRequest); | ||
} | ||
/** | ||
* Queries events by event key | ||
* @param eventKey Event key for an event stream. It is BCS serialized bytes | ||
* of `guid` field in the Move struct `EventHandle` | ||
* @returns Array of events assotiated with given key | ||
*/ | ||
async getEventsByEventKey(eventKey) { | ||
@@ -148,2 +246,15 @@ const response = await this.events.getEventsByEventKey(eventKey); | ||
} | ||
/** | ||
* Extracts event key from the account resource identified by the | ||
* `event_handle_struct` and `field_name`, then returns events identified by the event key | ||
* @param address Hex-encoded 16 bytes Aptos account from which events are queried | ||
* @param eventHandleStruct String representation of an on-chain Move struct type. | ||
* (e.g. `0x1::Coin::CoinStore<0x1::TestCoin::TestCoin>`) | ||
* @param fieldName The field name of the EventHandle in the struct | ||
* @param query Optional query object | ||
* @param query.start The start sequence number in the EVENT STREAM, defaulting to the latest event. | ||
* The events are returned in the reverse order of sequence number | ||
* @param query.limit The number of events to be returned for the page default is 5 | ||
* @returns Array of events | ||
*/ | ||
async getEventsByEventHandle(address, eventHandleStruct, fieldName, query) { | ||
@@ -154,3 +265,7 @@ const response = await this.accounts.getEventsByEventHandle(hex_string_1.HexString.ensure(address).hex(), eventHandleStruct, fieldName, query); | ||
} | ||
/** Submits a signed transaction to the transaction endpoint that takes JSON payload. */ | ||
/** | ||
* Submits a signed transaction to the transaction endpoint that takes JSON payload | ||
* @param signedTxnRequest A transaction, signed by `signTransaction` method | ||
* @returns Transaction that is accepted and submitted to mempool | ||
*/ | ||
async submitTransaction(signedTxnRequest) { | ||
@@ -161,3 +276,7 @@ const response = await this.transactions.submitTransaction(signedTxnRequest); | ||
} | ||
/** Submits a signed transaction to the the endpoint that takes BCS payload. */ | ||
/** | ||
* Submits a signed transaction to the the endpoint that takes BCS payload | ||
* @param signedTxn A BCS transaction representation | ||
* @returns Transaction that is accepted and submitted to mempool | ||
*/ | ||
async submitSignedBCSTransaction(signedTxn) { | ||
@@ -177,2 +296,9 @@ // Need to construct a customized post request for transactions in BCS payload | ||
} | ||
/** | ||
* Queries on-chain transactions | ||
* @param query Optional pagination object | ||
* @param query.start The start transaction version of the page. Default is the latest ledger version | ||
* @param query.limit The max number of transactions should be returned for the page. Default is 25 | ||
* @returns Array of on-chain transactions | ||
*/ | ||
async getTransactions(query) { | ||
@@ -183,2 +309,11 @@ const response = await this.transactions.getTransactions(query); | ||
} | ||
/** | ||
* Queries transaction by hash or version. When given transaction hash, server first looks up | ||
* on-chain transaction by hash; if no on-chain transaction found, then look up transaction | ||
* by hash in the mempool (pending) transactions. | ||
* When given a transaction version, server looks up the transaction on-chain by version | ||
* @param txnHashOrVersion - Transaction hash should be hex-encoded bytes string with 0x prefix. | ||
* Transaction version is an uint64 number. | ||
* @returns Transaction from mempool or on-chain transaction | ||
*/ | ||
async getTransaction(txnHashOrVersion) { | ||
@@ -189,2 +324,14 @@ const response = await this.transactions.getTransaction(txnHashOrVersion); | ||
} | ||
/** | ||
* Defines if specified transaction is currently in pending state | ||
* @param txnHash A hash of transaction | ||
* | ||
* To create a transaction hash: | ||
* | ||
* 1. Create hash message bytes: "Aptos::Transaction" bytes + BCS bytes of Transaction. | ||
* 2. Apply hash algorithm SHA3-256 to the hash message bytes. | ||
* 3. Hex-encode the hash bytes with 0x prefix. | ||
* | ||
* @returns `true` if transaction is in pending state and `false` otherwise | ||
*/ | ||
async transactionPending(txnHash) { | ||
@@ -198,3 +345,15 @@ const response = await this.transactions.getTransaction(txnHash); | ||
} | ||
/** Waits up to 10 seconds for a transaction to move past pending state */ | ||
/** | ||
* Waits up to 10 seconds for a transaction to move past pending state | ||
* @param txnHash A hash of transaction | ||
* @returns A Promise, that will resolve if transaction is accepted to the blockchain, | ||
* and reject if more then 10 seconds passed | ||
* @example | ||
* ``` | ||
* const signedTxn = await this.aptosClient.signTransaction(account, txnRequest); | ||
* const res = await this.aptosClient.submitTransaction(signedTxn); | ||
* await this.aptosClient.waitForTransaction(res.hash); | ||
* // do smth after transaction is accepted into blockchain | ||
* ``` | ||
*/ | ||
async waitForTransaction(txnHash) { | ||
@@ -212,2 +371,16 @@ let count = 0; | ||
} | ||
/** | ||
* Queries the latest ledger information | ||
* @param params Request params | ||
* @returns Latest ledger information | ||
* @example Example of returned data | ||
* ``` | ||
* { | ||
* chain_id: 15, | ||
* epoch: 6, | ||
* ledger_version: "2235883", | ||
* ledger_timestamp:"1654580922321826" | ||
* } | ||
* ``` | ||
*/ | ||
async getLedgerInfo(params = {}) { | ||
@@ -222,2 +395,6 @@ const result = await this.client.request({ | ||
} | ||
/** | ||
* @param params Request params | ||
* @returns Current chain id | ||
*/ | ||
async getChainId(params = {}) { | ||
@@ -227,2 +404,13 @@ const result = await this.getLedgerInfo(params); | ||
} | ||
/** | ||
* Gets a table item for a table identified by the handle and the key for the item. | ||
* Key and value types need to be passed in to help with key serialization and value deserialization. | ||
* @param handle A pointer to where that table is stored | ||
* @param data Object, that describes table item | ||
* @param data.key_type Move type of table key (e.g. `vector<u8>`) | ||
* @param data.value_type Move type of table value (e.g. `u64`) | ||
* @param data.key Value of table key | ||
* @param params Request params | ||
* @returns Table item value rendered in JSON | ||
*/ | ||
async getTableItem(handle, data, params) { | ||
@@ -229,0 +417,0 @@ const tableItem = await this.tables.getTableItem(handle, data, params); |
@@ -7,4 +7,3 @@ "use strict"; | ||
const aptos_account_1 = require("./aptos_account"); | ||
const aptos_types_1 = require("./transaction_builder/aptos_types"); | ||
const bcs_1 = require("./transaction_builder/bcs"); | ||
const transaction_builder_1 = require("./transaction_builder"); | ||
test('gets genesis account', async () => { | ||
@@ -85,4 +84,4 @@ const client = new aptos_client_1.AptosClient(util_test_1.NODE_URL); | ||
expect(accountResource.data.coin.value).toBe('0'); | ||
const token = new aptos_types_1.TypeTagStruct(aptos_types_1.StructTag.fromString('0x1::TestCoin::TestCoin')); | ||
const scriptFunctionPayload = new aptos_types_1.TransactionPayloadScriptFunction(aptos_types_1.ScriptFunction.natual('0x1::Coin', 'transfer', [token], [(0, bcs_1.bcsToBytes)(aptos_types_1.AccountAddress.fromHex(account2.address())), (0, bcs_1.bcsSerializeUint64)(717)])); | ||
const token = new transaction_builder_1.TxnBuilderTypes.TypeTagStruct(transaction_builder_1.TxnBuilderTypes.StructTag.fromString('0x1::TestCoin::TestCoin')); | ||
const scriptFunctionPayload = new transaction_builder_1.TxnBuilderTypes.TransactionPayloadScriptFunction(transaction_builder_1.TxnBuilderTypes.ScriptFunction.natual('0x1::Coin', 'transfer', [token], [transaction_builder_1.BCS.bcsToBytes(transaction_builder_1.TxnBuilderTypes.AccountAddress.fromHex(account2.address())), transaction_builder_1.BCS.bcsSerializeUint64(717)])); | ||
const [{ sequence_number: sequnceNumber }, chainId] = await Promise.all([ | ||
@@ -92,4 +91,4 @@ client.getAccount(account1.address()), | ||
]); | ||
const rawTxn = new aptos_types_1.RawTransaction(aptos_types_1.AccountAddress.fromHex(account1.address()), BigInt(sequnceNumber), scriptFunctionPayload, 1000n, 1n, BigInt(Math.floor(Date.now() / 1000) + 10), new aptos_types_1.ChainId(chainId)); | ||
const bcsTxn = await aptos_client_1.AptosClient.generateBCSTransaction(account1, rawTxn); | ||
const rawTxn = new transaction_builder_1.TxnBuilderTypes.RawTransaction(transaction_builder_1.TxnBuilderTypes.AccountAddress.fromHex(account1.address()), BigInt(sequnceNumber), scriptFunctionPayload, 1000n, 1n, BigInt(Math.floor(Date.now() / 1000) + 10), new transaction_builder_1.TxnBuilderTypes.ChainId(chainId)); | ||
const bcsTxn = aptos_client_1.AptosClient.generateBCSTransaction(account1, rawTxn); | ||
const transactionRes = await client.submitSignedBCSTransaction(bcsTxn); | ||
@@ -101,2 +100,48 @@ await client.waitForTransaction(transactionRes.hash); | ||
}, 30 * 1000); | ||
test('submits multisig transaction', async () => { | ||
const client = new aptos_client_1.AptosClient(util_test_1.NODE_URL); | ||
const faucetClient = new faucet_client_1.FaucetClient(util_test_1.NODE_URL, util_test_1.FAUCET_URL, null); | ||
const account1 = new aptos_account_1.AptosAccount(); | ||
const account2 = new aptos_account_1.AptosAccount(); | ||
const account3 = new aptos_account_1.AptosAccount(); | ||
const multiSigPublicKey = new transaction_builder_1.TxnBuilderTypes.MultiEd25519PublicKey([ | ||
new transaction_builder_1.TxnBuilderTypes.Ed25519PublicKey(account1.signingKey.publicKey), | ||
new transaction_builder_1.TxnBuilderTypes.Ed25519PublicKey(account2.signingKey.publicKey), | ||
new transaction_builder_1.TxnBuilderTypes.Ed25519PublicKey(account3.signingKey.publicKey), | ||
], 2); | ||
const authKey = transaction_builder_1.TxnBuilderTypes.AuthenticationKey.fromMultiEd25519PublicKey(multiSigPublicKey); | ||
const mutisigAccountAddress = authKey.derivedAddress(); | ||
await faucetClient.fundAccount(mutisigAccountAddress, 5000); | ||
let resources = await client.getAccountResources(mutisigAccountAddress); | ||
let accountResource = resources.find((r) => r.type === '0x1::Coin::CoinStore<0x1::TestCoin::TestCoin>'); | ||
expect(accountResource.data.coin.value).toBe('5000'); | ||
const account4 = new aptos_account_1.AptosAccount(); | ||
await faucetClient.fundAccount(account4.address(), 0); | ||
resources = await client.getAccountResources(account4.address()); | ||
accountResource = resources.find((r) => r.type === '0x1::Coin::CoinStore<0x1::TestCoin::TestCoin>'); | ||
expect(accountResource.data.coin.value).toBe('0'); | ||
const token = new transaction_builder_1.TxnBuilderTypes.TypeTagStruct(transaction_builder_1.TxnBuilderTypes.StructTag.fromString('0x1::TestCoin::TestCoin')); | ||
const scriptFunctionPayload = new transaction_builder_1.TxnBuilderTypes.TransactionPayloadScriptFunction(transaction_builder_1.TxnBuilderTypes.ScriptFunction.natual('0x1::Coin', 'transfer', [token], [transaction_builder_1.BCS.bcsToBytes(transaction_builder_1.TxnBuilderTypes.AccountAddress.fromHex(account4.address())), transaction_builder_1.BCS.bcsSerializeUint64(123)])); | ||
const [{ sequence_number: sequnceNumber }, chainId] = await Promise.all([ | ||
client.getAccount(mutisigAccountAddress), | ||
client.getChainId(), | ||
]); | ||
const rawTxn = new transaction_builder_1.TxnBuilderTypes.RawTransaction(transaction_builder_1.TxnBuilderTypes.AccountAddress.fromHex(mutisigAccountAddress), BigInt(sequnceNumber), scriptFunctionPayload, 1000n, 1n, BigInt(Math.floor(Date.now() / 1000) + 10), new transaction_builder_1.TxnBuilderTypes.ChainId(chainId)); | ||
const txnBuilder = new transaction_builder_1.TransactionBuilderMultiEd25519((signingMessage) => { | ||
const sigHexStr1 = account1.signBuffer(signingMessage); | ||
const sigHexStr3 = account3.signBuffer(signingMessage); | ||
const bitmap = transaction_builder_1.TxnBuilderTypes.MultiEd25519Signature.createBitmap([0, 2]); | ||
const muliEd25519Sig = new transaction_builder_1.TxnBuilderTypes.MultiEd25519Signature([ | ||
new transaction_builder_1.TxnBuilderTypes.Ed25519Signature(sigHexStr1.toUint8Array()), | ||
new transaction_builder_1.TxnBuilderTypes.Ed25519Signature(sigHexStr3.toUint8Array()), | ||
], bitmap); | ||
return muliEd25519Sig; | ||
}, multiSigPublicKey); | ||
const bcsTxn = txnBuilder.sign(rawTxn); | ||
const transactionRes = await client.submitSignedBCSTransaction(bcsTxn); | ||
await client.waitForTransaction(transactionRes.hash); | ||
resources = await client.getAccountResources(account4.address()); | ||
accountResource = resources.find((r) => r.type === '0x1::Coin::CoinStore<0x1::TestCoin::TestCoin>'); | ||
expect(accountResource.data.coin.value).toBe('123'); | ||
}, 30 * 1000); | ||
//# sourceMappingURL=aptos_client.test.js.map |
import { AptosClient, AptosClientConfig } from './aptos_client'; | ||
import { Types } from './types'; | ||
import { MaybeHexString } from './hex_string'; | ||
/** | ||
* Class for requsting tokens from faucet | ||
*/ | ||
export declare class FaucetClient extends AptosClient { | ||
faucetUrl: string; | ||
/** | ||
* Establishes a connection to Aptos node | ||
* @param nodeUrl A url of the Aptos Node API endpoint | ||
* @param faucetUrl A faucet url | ||
* @param config An optional config for inner axios instance | ||
* Detailed config description: {@link https://github.com/axios/axios#request-config} | ||
*/ | ||
constructor(nodeUrl: string, faucetUrl: string, config?: AptosClientConfig); | ||
/** This creates an account if it does not exist and mints the specified amount of | ||
coins into that account */ | ||
/** | ||
* This creates an account if it does not exist and mints the specified amount of | ||
* coins into that account | ||
* @param address Hex-encoded 16 bytes Aptos account address wich mints tokens | ||
* @param amount Amount of tokens to mint | ||
* @returns Hashes of submitted transactions | ||
*/ | ||
fundAccount(address: MaybeHexString, amount: number): Promise<Types.HexEncodedBytes[]>; | ||
} | ||
//# sourceMappingURL=faucet_client.d.ts.map |
@@ -11,3 +11,13 @@ "use strict"; | ||
const hex_string_1 = require("./hex_string"); | ||
/** | ||
* Class for requsting tokens from faucet | ||
*/ | ||
class FaucetClient extends aptos_client_1.AptosClient { | ||
/** | ||
* Establishes a connection to Aptos node | ||
* @param nodeUrl A url of the Aptos Node API endpoint | ||
* @param faucetUrl A faucet url | ||
* @param config An optional config for inner axios instance | ||
* Detailed config description: {@link https://github.com/axios/axios#request-config} | ||
*/ | ||
constructor(nodeUrl, faucetUrl, config) { | ||
@@ -17,4 +27,9 @@ super(nodeUrl, config); | ||
} | ||
/** This creates an account if it does not exist and mints the specified amount of | ||
coins into that account */ | ||
/** | ||
* This creates an account if it does not exist and mints the specified amount of | ||
* coins into that account | ||
* @param address Hex-encoded 16 bytes Aptos account address wich mints tokens | ||
* @param amount Amount of tokens to mint | ||
* @returns Hashes of submitted transactions | ||
*/ | ||
async fundAccount(address, amount) { | ||
@@ -21,0 +36,0 @@ const url = `${this.faucetUrl}/mint?amount=${amount}&address=${hex_string_1.HexString.ensure(address).noPrefix()}`; |
import { Buffer } from 'buffer/'; | ||
import { Types } from './types'; | ||
export declare type MaybeHexString = HexString | string | Types.HexEncodedBytes; | ||
/** | ||
* A util class for working with hex strings. | ||
* Hex strings are strings that are prefixed with `0x` | ||
*/ | ||
export declare class HexString { | ||
private readonly hexString; | ||
/** | ||
* Creates new hex string from Buffer | ||
* @param buffer A buffer to convert | ||
* @returns New HexString | ||
*/ | ||
static fromBuffer(buffer: Buffer): HexString; | ||
/** | ||
* Creates new hex string from Uint8Array | ||
* @param arr Uint8Array to convert | ||
* @returns New HexString | ||
*/ | ||
static fromUint8Array(arr: Uint8Array): HexString; | ||
/** | ||
* Ensures `hexString` is instance of `HexString` class | ||
* @param hexString String to check | ||
* @returns New HexString if `hexString` is regular string or `hexString` if it is HexString instance | ||
* @example | ||
* ``` | ||
* const regularString = "string"; | ||
* const hexString = new HexString("string"); // "0xstring" | ||
* HexString.ensure(regularString); // "0xstring" | ||
* HexString.ensure(hexString); // "0xstring" | ||
* ``` | ||
*/ | ||
static ensure(hexString: MaybeHexString): HexString; | ||
/** | ||
* Creates new HexString instance from regular string. If specified string already starts with "0x" prefix, | ||
* it will not add another one | ||
* @param hexString String to convert | ||
* @example | ||
* ``` | ||
* const string = "string"; | ||
* new HexString(string); // "0xstring" | ||
* ``` | ||
*/ | ||
constructor(hexString: string | Types.HexEncodedBytes); | ||
/** | ||
* Getter for inner hexString | ||
* @returns Inner hex string | ||
*/ | ||
hex(): string; | ||
/** | ||
* Getter for inner hexString without prefix | ||
* @returns Inner hex string without prefix | ||
* @example | ||
* ``` | ||
* const hexString = new HexString("string"); // "0xstring" | ||
* hexString.noPrefix(); // "string" | ||
* ``` | ||
*/ | ||
noPrefix(): string; | ||
/** | ||
* Overrides default `toString` method | ||
* @returns Inner hex string | ||
*/ | ||
toString(): string; | ||
/** | ||
* Trimmes extra zeroes in the begining of a string | ||
* @returns Inner hexString without leading zeroes | ||
* @example | ||
* ``` | ||
* new HexString("0x000000string").toShortString(); // result = "0xstring" | ||
* ``` | ||
*/ | ||
toShortString(): string; | ||
/** | ||
* Converts hex string to a Buffer in hex encoding | ||
* @returns Buffer from inner hexString without prefix | ||
*/ | ||
toBuffer(): Buffer; | ||
/** | ||
* Converts hex string to a Uint8Array | ||
* @returns Uint8Array from inner hexString without prefix | ||
*/ | ||
toUint8Array(): Uint8Array; | ||
} | ||
//# sourceMappingURL=hex_string.d.ts.map |
@@ -5,3 +5,17 @@ "use strict"; | ||
const buffer_1 = require("buffer/"); // the trailing slash is important! | ||
/** | ||
* A util class for working with hex strings. | ||
* Hex strings are strings that are prefixed with `0x` | ||
*/ | ||
class HexString { | ||
/** | ||
* Creates new HexString instance from regular string. If specified string already starts with "0x" prefix, | ||
* it will not add another one | ||
* @param hexString String to convert | ||
* @example | ||
* ``` | ||
* const string = "string"; | ||
* new HexString(string); // "0xstring" | ||
* ``` | ||
*/ | ||
constructor(hexString) { | ||
@@ -15,8 +29,30 @@ if (hexString.startsWith('0x')) { | ||
} | ||
/** | ||
* Creates new hex string from Buffer | ||
* @param buffer A buffer to convert | ||
* @returns New HexString | ||
*/ | ||
static fromBuffer(buffer) { | ||
return new HexString(buffer.toString('hex')); | ||
} | ||
/** | ||
* Creates new hex string from Uint8Array | ||
* @param arr Uint8Array to convert | ||
* @returns New HexString | ||
*/ | ||
static fromUint8Array(arr) { | ||
return HexString.fromBuffer(buffer_1.Buffer.from(arr)); | ||
} | ||
/** | ||
* Ensures `hexString` is instance of `HexString` class | ||
* @param hexString String to check | ||
* @returns New HexString if `hexString` is regular string or `hexString` if it is HexString instance | ||
* @example | ||
* ``` | ||
* const regularString = "string"; | ||
* const hexString = new HexString("string"); // "0xstring" | ||
* HexString.ensure(regularString); // "0xstring" | ||
* HexString.ensure(hexString); // "0xstring" | ||
* ``` | ||
*/ | ||
static ensure(hexString) { | ||
@@ -28,11 +64,36 @@ if (typeof hexString === 'string') { | ||
} | ||
/** | ||
* Getter for inner hexString | ||
* @returns Inner hex string | ||
*/ | ||
hex() { | ||
return this.hexString; | ||
} | ||
/** | ||
* Getter for inner hexString without prefix | ||
* @returns Inner hex string without prefix | ||
* @example | ||
* ``` | ||
* const hexString = new HexString("string"); // "0xstring" | ||
* hexString.noPrefix(); // "string" | ||
* ``` | ||
*/ | ||
noPrefix() { | ||
return this.hexString.slice(2); | ||
} | ||
/** | ||
* Overrides default `toString` method | ||
* @returns Inner hex string | ||
*/ | ||
toString() { | ||
return this.hex(); | ||
} | ||
/** | ||
* Trimmes extra zeroes in the begining of a string | ||
* @returns Inner hexString without leading zeroes | ||
* @example | ||
* ``` | ||
* new HexString("0x000000string").toShortString(); // result = "0xstring" | ||
* ``` | ||
*/ | ||
toShortString() { | ||
@@ -42,5 +103,13 @@ const trimmed = this.hexString.replace(/^0x0*/, ''); | ||
} | ||
/** | ||
* Converts hex string to a Buffer in hex encoding | ||
* @returns Buffer from inner hexString without prefix | ||
*/ | ||
toBuffer() { | ||
return buffer_1.Buffer.from(this.noPrefix(), 'hex'); | ||
} | ||
/** | ||
* Converts hex string to a Uint8Array | ||
* @returns Uint8Array from inner hexString without prefix | ||
*/ | ||
toUint8Array() { | ||
@@ -47,0 +116,0 @@ return Uint8Array.from(this.toBuffer()); |
@@ -7,2 +7,3 @@ export * from './aptos_account'; | ||
export * from './types'; | ||
export * from './transaction_builder'; | ||
//# sourceMappingURL=index.d.ts.map |
@@ -24,2 +24,3 @@ "use strict"; | ||
__exportStar(require("./types"), exports); | ||
__exportStar(require("./transaction_builder"), exports); | ||
//# sourceMappingURL=index.js.map |
@@ -5,15 +5,130 @@ import { AptosAccount } from './aptos_account'; | ||
import { MaybeHexString } from './hex_string'; | ||
/** | ||
* Class for creating, minting and managing minting NFT collections and tokens | ||
*/ | ||
export declare class TokenClient { | ||
aptosClient: AptosClient; | ||
/** | ||
* Creates new TokenClient instance | ||
* @param aptosClient AptosClient instance | ||
*/ | ||
constructor(aptosClient: AptosClient); | ||
/** | ||
* Brings together methods for generating, signing and submitting transaction | ||
* @param account AptosAccount which will sign a transaction | ||
* @param payload Transaction payload. It depends on transaction type you want to send | ||
* @returns Promise that resolves to transaction hash | ||
*/ | ||
submitTransactionHelper(account: AptosAccount, payload: Types.TransactionPayload): Promise<string>; | ||
/** | ||
* Creates a new NFT collection within the specified account | ||
* @param account AptosAccount where collection will be created | ||
* @param name Collection name | ||
* @param description Collection description | ||
* @param uri URL to additional info about collection | ||
* @returns A hash of transaction | ||
*/ | ||
createCollection(account: AptosAccount, name: string, description: string, uri: string): Promise<Types.HexEncodedBytes>; | ||
/** | ||
* Creates a new NFT within the specified account | ||
* @param account AptosAccount where token will be created | ||
* @param collectionName Name of collection, that token belongs to | ||
* @param name Token name | ||
* @param description Token description | ||
* @param supply Token supply | ||
* @param uri URL to additional info about token | ||
* @returns A hash of transaction | ||
*/ | ||
createToken(account: AptosAccount, collectionName: string, name: string, description: string, supply: number, uri: string): Promise<Types.HexEncodedBytes>; | ||
/** | ||
* Transfers specified amount of tokens from account to receiver | ||
* @param account AptosAccount where token from which tokens will be transfered | ||
* @param receiver Hex-encoded 16 bytes Aptos account address to which tokens will be transfered | ||
* @param creator Hex-encoded 16 bytes Aptos account address to which created tokens | ||
* @param collectionName Name of collection where token is stored | ||
* @param name Token name | ||
* @param amount Amount of tokens which will be transfered | ||
* @returns A hash of transaction | ||
*/ | ||
offerToken(account: AptosAccount, receiver: MaybeHexString, creator: MaybeHexString, collectionName: string, name: string, amount: number): Promise<Types.HexEncodedBytes>; | ||
/** | ||
* Claims a token on specified account | ||
* @param account AptosAccount which will claim token | ||
* @param sender Hex-encoded 16 bytes Aptos account address which holds a token | ||
* @param creator Hex-encoded 16 bytes Aptos account address which created a token | ||
* @param collectionName Name of collection where token is stored | ||
* @param name Token name | ||
* @returns A hash of transaction | ||
*/ | ||
claimToken(account: AptosAccount, sender: MaybeHexString, creator: MaybeHexString, collectionName: string, name: string): Promise<Types.HexEncodedBytes>; | ||
/** | ||
* Removes a token from pending claims list | ||
* @param account AptosAccount which will remove token from pending list | ||
* @param receiver Hex-encoded 16 bytes Aptos account address which had to claim token | ||
* @param creator Hex-encoded 16 bytes Aptos account address which created a token | ||
* @param collectionName Name of collection where token is strored | ||
* @param name Token name | ||
* @returns A hash of transaction | ||
*/ | ||
cancelTokenOffer(account: AptosAccount, receiver: MaybeHexString, creator: MaybeHexString, collectionName: string, name: string): Promise<Types.HexEncodedBytes>; | ||
/** | ||
* Queries collection data | ||
* @param creator Hex-encoded 16 bytes Aptos account address which created a collection | ||
* @param collectionName Collection name | ||
* @returns Collection data in below format | ||
* ``` | ||
* Collection { | ||
* // Describes the collection | ||
* description: string, | ||
* // Unique name within this creators account for this collection | ||
* name: string, | ||
* // URL for additional information/media | ||
* uri: string, | ||
* // Total number of distinct Tokens tracked by the collection | ||
* count: number, | ||
* // Optional maximum number of tokens allowed within this collections | ||
* maximum: number | ||
* } | ||
* ``` | ||
*/ | ||
getCollectionData(creator: MaybeHexString, collectionName: string): Promise<any>; | ||
getTokenData(creator: MaybeHexString, collectionName: string, tokenName: string): Promise<number>; | ||
getTokenBalance(creator: MaybeHexString, collectionName: string, tokenName: string): Promise<number>; | ||
/** | ||
* Queries token data from collection | ||
* @param creator Hex-encoded 16 bytes Aptos account address which created a token | ||
* @param collectionName Name of collection, which holds a token | ||
* @param tokenName Token name | ||
* @returns Token data in below format | ||
* ``` | ||
* TokenData { | ||
* // Unique name within this creators account for this Token's collection | ||
* collection: string; | ||
* // Describes this Token | ||
* description: string; | ||
* // The name of this Token | ||
* name: string; | ||
* // Optional maximum number of this type of Token. | ||
* maximum: number; | ||
* // Total number of this type of Token | ||
* supply: number; | ||
* /// URL for additional information / media | ||
* uri: string; | ||
* } | ||
* ``` | ||
*/ | ||
getTokenData(creator: MaybeHexString, collectionName: string, tokenName: string): Promise<Types.TokenData>; | ||
/** | ||
* Queries specific token from account's TokenStore | ||
* @param creator Hex-encoded 16 bytes Aptos account address which created a token | ||
* @param collectionName Name of collection, which holds a token | ||
* @param tokenName Token name | ||
* @returns Token object in below format | ||
* ``` | ||
* Token { | ||
* id: TokenId; | ||
* value: number; | ||
* } | ||
* ``` | ||
*/ | ||
getTokenBalance(creator: MaybeHexString, collectionName: string, tokenName: string): Promise<Types.Token>; | ||
} | ||
//# sourceMappingURL=token_client.d.ts.map |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.TokenClient = void 0; | ||
/** | ||
* Class for creating, minting and managing minting NFT collections and tokens | ||
*/ | ||
class TokenClient { | ||
/** | ||
* Creates new TokenClient instance | ||
* @param aptosClient AptosClient instance | ||
*/ | ||
constructor(aptosClient) { | ||
this.aptosClient = aptosClient; | ||
} | ||
/** | ||
* Brings together methods for generating, signing and submitting transaction | ||
* @param account AptosAccount which will sign a transaction | ||
* @param payload Transaction payload. It depends on transaction type you want to send | ||
* @returns Promise that resolves to transaction hash | ||
*/ | ||
async submitTransactionHelper(account, payload) { | ||
@@ -17,3 +30,10 @@ const txnRequest = await this.aptosClient.generateTransaction(account.address(), payload, { | ||
} | ||
// Creates a new collection within the specified account | ||
/** | ||
* Creates a new NFT collection within the specified account | ||
* @param account AptosAccount where collection will be created | ||
* @param name Collection name | ||
* @param description Collection description | ||
* @param uri URL to additional info about collection | ||
* @returns A hash of transaction | ||
*/ | ||
async createCollection(account, name, description, uri) { | ||
@@ -33,3 +53,12 @@ const payload = { | ||
} | ||
// Creates a new token within the specified account | ||
/** | ||
* Creates a new NFT within the specified account | ||
* @param account AptosAccount where token will be created | ||
* @param collectionName Name of collection, that token belongs to | ||
* @param name Token name | ||
* @param description Token description | ||
* @param supply Token supply | ||
* @param uri URL to additional info about token | ||
* @returns A hash of transaction | ||
*/ | ||
async createToken(account, collectionName, name, description, supply, uri) { | ||
@@ -52,3 +81,12 @@ const payload = { | ||
} | ||
// Offer token to another account | ||
/** | ||
* Transfers specified amount of tokens from account to receiver | ||
* @param account AptosAccount where token from which tokens will be transfered | ||
* @param receiver Hex-encoded 16 bytes Aptos account address to which tokens will be transfered | ||
* @param creator Hex-encoded 16 bytes Aptos account address to which created tokens | ||
* @param collectionName Name of collection where token is stored | ||
* @param name Token name | ||
* @param amount Amount of tokens which will be transfered | ||
* @returns A hash of transaction | ||
*/ | ||
async offerToken(account, receiver, creator, collectionName, name, amount) { | ||
@@ -70,3 +108,11 @@ const payload = { | ||
} | ||
// Claim token | ||
/** | ||
* Claims a token on specified account | ||
* @param account AptosAccount which will claim token | ||
* @param sender Hex-encoded 16 bytes Aptos account address which holds a token | ||
* @param creator Hex-encoded 16 bytes Aptos account address which created a token | ||
* @param collectionName Name of collection where token is stored | ||
* @param name Token name | ||
* @returns A hash of transaction | ||
*/ | ||
async claimToken(account, sender, creator, collectionName, name) { | ||
@@ -82,3 +128,11 @@ const payload = { | ||
} | ||
// Cancel token | ||
/** | ||
* Removes a token from pending claims list | ||
* @param account AptosAccount which will remove token from pending list | ||
* @param receiver Hex-encoded 16 bytes Aptos account address which had to claim token | ||
* @param creator Hex-encoded 16 bytes Aptos account address which created a token | ||
* @param collectionName Name of collection where token is strored | ||
* @param name Token name | ||
* @returns A hash of transaction | ||
*/ | ||
async cancelTokenOffer(account, receiver, creator, collectionName, name) { | ||
@@ -94,2 +148,22 @@ const payload = { | ||
} | ||
/** | ||
* Queries collection data | ||
* @param creator Hex-encoded 16 bytes Aptos account address which created a collection | ||
* @param collectionName Collection name | ||
* @returns Collection data in below format | ||
* ``` | ||
* Collection { | ||
* // Describes the collection | ||
* description: string, | ||
* // Unique name within this creators account for this collection | ||
* name: string, | ||
* // URL for additional information/media | ||
* uri: string, | ||
* // Total number of distinct Tokens tracked by the collection | ||
* count: number, | ||
* // Optional maximum number of tokens allowed within this collections | ||
* maximum: number | ||
* } | ||
* ``` | ||
*/ | ||
async getCollectionData(creator, collectionName) { | ||
@@ -108,3 +182,25 @@ const resources = await this.aptosClient.getAccountResources(creator); | ||
} | ||
// Retrieve the token's creation_num, which is useful for non-creator operations | ||
/** | ||
* Queries token data from collection | ||
* @param creator Hex-encoded 16 bytes Aptos account address which created a token | ||
* @param collectionName Name of collection, which holds a token | ||
* @param tokenName Token name | ||
* @returns Token data in below format | ||
* ``` | ||
* TokenData { | ||
* // Unique name within this creators account for this Token's collection | ||
* collection: string; | ||
* // Describes this Token | ||
* description: string; | ||
* // The name of this Token | ||
* name: string; | ||
* // Optional maximum number of this type of Token. | ||
* maximum: number; | ||
* // Total number of this type of Token | ||
* supply: number; | ||
* /// URL for additional information / media | ||
* uri: string; | ||
* } | ||
* ``` | ||
*/ | ||
async getTokenData(creator, collectionName, tokenName) { | ||
@@ -126,3 +222,15 @@ const collection = await this.aptosClient.getAccountResource(creator, '0x1::Token::Collections'); | ||
} | ||
// Retrieve the token's creation_num, which is useful for non-creator operations | ||
/** | ||
* Queries specific token from account's TokenStore | ||
* @param creator Hex-encoded 16 bytes Aptos account address which created a token | ||
* @param collectionName Name of collection, which holds a token | ||
* @param tokenName Token name | ||
* @returns Token object in below format | ||
* ``` | ||
* Token { | ||
* id: TokenId; | ||
* value: number; | ||
* } | ||
* ``` | ||
*/ | ||
async getTokenBalance(creator, collectionName, tokenName) { | ||
@@ -129,0 +237,0 @@ const tokenStore = await this.aptosClient.getAccountResource(creator, '0x1::Token::TokenStore'); |
@@ -1,3 +0,5 @@ | ||
import { Serializer, Deserializer, Bytes, Seq } from '../bcs'; | ||
import { Serializer, Deserializer, Seq } from '../bcs'; | ||
import { AccountAddress } from './account_address'; | ||
import { Ed25519PublicKey, Ed25519Signature } from './ed25519'; | ||
import { MultiEd25519PublicKey, MultiEd25519Signature } from './multi_ed25519'; | ||
export declare abstract class TransactionAuthenticator { | ||
@@ -28,30 +30,5 @@ abstract serialize(serializer: Serializer): void; | ||
* | ||
* @param public_key BCS bytes for a list of public keys. | ||
* @param public_key | ||
* @param signature | ||
* | ||
* @example | ||
* Developers must manually construct the input to get the BCS bytes. | ||
* See below code example for the BCS input. | ||
* ```ts | ||
* interface MultiEd25519PublicKey { | ||
* // A list of public keys | ||
* public_keys: Uint8Array[], | ||
* // At least `threshold` signatures must be valid | ||
* threshold: Uint8, | ||
* } | ||
* ``` | ||
* @param signature BCS bytes of multiple signatures. | ||
* | ||
* @example | ||
* Developers must manually construct the input to get the BCS bytes. | ||
* See below code example for the BCS input. | ||
* ```ts | ||
* interface MultiEd25519Signature { | ||
* // A list of signatures | ||
* signatures: Uint8Array[], | ||
* // 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. | ||
* bitmap: Uint8Array, | ||
* } | ||
* ``` | ||
*/ | ||
@@ -88,26 +65,2 @@ constructor(public_key: MultiEd25519PublicKey, signature: MultiEd25519Signature); | ||
} | ||
export declare class Ed25519PublicKey { | ||
readonly value: Bytes; | ||
constructor(value: Bytes); | ||
serialize(serializer: Serializer): void; | ||
static deserialize(deserializer: Deserializer): Ed25519PublicKey; | ||
} | ||
export declare class Ed25519Signature { | ||
readonly value: Bytes; | ||
constructor(value: Bytes); | ||
serialize(serializer: Serializer): void; | ||
static deserialize(deserializer: Deserializer): Ed25519Signature; | ||
} | ||
export declare class MultiEd25519PublicKey { | ||
readonly value: Bytes; | ||
constructor(value: Bytes); | ||
serialize(serializer: Serializer): void; | ||
static deserialize(deserializer: Deserializer): MultiEd25519PublicKey; | ||
} | ||
export declare class MultiEd25519Signature { | ||
readonly value: Bytes; | ||
constructor(value: Bytes); | ||
serialize(serializer: Serializer): void; | ||
static deserialize(deserializer: Deserializer): MultiEd25519Signature; | ||
} | ||
//# sourceMappingURL=authenticator.d.ts.map |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.MultiEd25519Signature = exports.MultiEd25519PublicKey = exports.Ed25519Signature = exports.Ed25519PublicKey = exports.AccountAuthenticatorMultiEd25519 = exports.AccountAuthenticatorEd25519 = exports.AccountAuthenticator = exports.TransactionAuthenticatorMultiAgent = exports.TransactionAuthenticatorMultiEd25519 = exports.TransactionAuthenticatorEd25519 = exports.TransactionAuthenticator = void 0; | ||
exports.AccountAuthenticatorMultiEd25519 = exports.AccountAuthenticatorEd25519 = exports.AccountAuthenticator = exports.TransactionAuthenticatorMultiAgent = exports.TransactionAuthenticatorMultiEd25519 = exports.TransactionAuthenticatorEd25519 = exports.TransactionAuthenticator = void 0; | ||
/* eslint-disable @typescript-eslint/naming-convention */ | ||
/* eslint-disable max-classes-per-file */ | ||
const bcs_1 = require("../bcs"); | ||
const account_address_1 = require("./account_address"); | ||
const ed25519_1 = require("./ed25519"); | ||
const multi_ed25519_1 = require("./multi_ed25519"); | ||
class TransactionAuthenticator { | ||
@@ -44,4 +45,4 @@ static deserialize(deserializer) { | ||
static load(deserializer) { | ||
const public_key = Ed25519PublicKey.deserialize(deserializer); | ||
const signature = Ed25519Signature.deserialize(deserializer); | ||
const public_key = ed25519_1.Ed25519PublicKey.deserialize(deserializer); | ||
const signature = ed25519_1.Ed25519Signature.deserialize(deserializer); | ||
return new TransactionAuthenticatorEd25519(public_key, signature); | ||
@@ -55,30 +56,5 @@ } | ||
* | ||
* @param public_key BCS bytes for a list of public keys. | ||
* @param public_key | ||
* @param signature | ||
* | ||
* @example | ||
* Developers must manually construct the input to get the BCS bytes. | ||
* See below code example for the BCS input. | ||
* ```ts | ||
* interface MultiEd25519PublicKey { | ||
* // A list of public keys | ||
* public_keys: Uint8Array[], | ||
* // At least `threshold` signatures must be valid | ||
* threshold: Uint8, | ||
* } | ||
* ``` | ||
* @param signature BCS bytes of multiple signatures. | ||
* | ||
* @example | ||
* Developers must manually construct the input to get the BCS bytes. | ||
* See below code example for the BCS input. | ||
* ```ts | ||
* interface MultiEd25519Signature { | ||
* // A list of signatures | ||
* signatures: Uint8Array[], | ||
* // 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. | ||
* bitmap: Uint8Array, | ||
* } | ||
* ``` | ||
*/ | ||
@@ -96,4 +72,4 @@ constructor(public_key, signature) { | ||
static load(deserializer) { | ||
const public_key = MultiEd25519PublicKey.deserialize(deserializer); | ||
const signature = MultiEd25519Signature.deserialize(deserializer); | ||
const public_key = multi_ed25519_1.MultiEd25519PublicKey.deserialize(deserializer); | ||
const signature = multi_ed25519_1.MultiEd25519Signature.deserialize(deserializer); | ||
return new TransactionAuthenticatorMultiEd25519(public_key, signature); | ||
@@ -150,4 +126,4 @@ } | ||
static load(deserializer) { | ||
const public_key = Ed25519PublicKey.deserialize(deserializer); | ||
const signature = Ed25519Signature.deserialize(deserializer); | ||
const public_key = ed25519_1.Ed25519PublicKey.deserialize(deserializer); | ||
const signature = ed25519_1.Ed25519Signature.deserialize(deserializer); | ||
return new AccountAuthenticatorEd25519(public_key, signature); | ||
@@ -169,4 +145,4 @@ } | ||
static load(deserializer) { | ||
const public_key = MultiEd25519PublicKey.deserialize(deserializer); | ||
const signature = MultiEd25519Signature.deserialize(deserializer); | ||
const public_key = multi_ed25519_1.MultiEd25519PublicKey.deserialize(deserializer); | ||
const signature = multi_ed25519_1.MultiEd25519Signature.deserialize(deserializer); | ||
return new AccountAuthenticatorMultiEd25519(public_key, signature); | ||
@@ -176,54 +152,2 @@ } | ||
exports.AccountAuthenticatorMultiEd25519 = AccountAuthenticatorMultiEd25519; | ||
class Ed25519PublicKey { | ||
constructor(value) { | ||
this.value = value; | ||
} | ||
serialize(serializer) { | ||
serializer.serializeBytes(this.value); | ||
} | ||
static deserialize(deserializer) { | ||
const value = deserializer.deserializeBytes(); | ||
return new Ed25519PublicKey(value); | ||
} | ||
} | ||
exports.Ed25519PublicKey = Ed25519PublicKey; | ||
class Ed25519Signature { | ||
constructor(value) { | ||
this.value = value; | ||
} | ||
serialize(serializer) { | ||
serializer.serializeBytes(this.value); | ||
} | ||
static deserialize(deserializer) { | ||
const value = deserializer.deserializeBytes(); | ||
return new Ed25519Signature(value); | ||
} | ||
} | ||
exports.Ed25519Signature = Ed25519Signature; | ||
class MultiEd25519PublicKey { | ||
constructor(value) { | ||
this.value = value; | ||
} | ||
serialize(serializer) { | ||
serializer.serializeBytes(this.value); | ||
} | ||
static deserialize(deserializer) { | ||
const value = deserializer.deserializeBytes(); | ||
return new MultiEd25519PublicKey(value); | ||
} | ||
} | ||
exports.MultiEd25519PublicKey = MultiEd25519PublicKey; | ||
class MultiEd25519Signature { | ||
constructor(value) { | ||
this.value = value; | ||
} | ||
serialize(serializer) { | ||
serializer.serializeBytes(this.value); | ||
} | ||
static deserialize(deserializer) { | ||
const value = deserializer.deserializeBytes(); | ||
return new MultiEd25519Signature(value); | ||
} | ||
} | ||
exports.MultiEd25519Signature = MultiEd25519Signature; | ||
//# sourceMappingURL=authenticator.js.map |
@@ -0,1 +1,2 @@ | ||
import { Buffer } from 'buffer/'; | ||
export * from './account_address'; | ||
@@ -6,2 +7,6 @@ export * from './authenticator'; | ||
export * from './identifier'; | ||
export * from './ed25519'; | ||
export * from './multi_ed25519'; | ||
export * from './authentication_key'; | ||
export declare type SigningMessage = Buffer; | ||
//# sourceMappingURL=index.d.ts.map |
@@ -22,2 +22,5 @@ "use strict"; | ||
__exportStar(require("./identifier"), exports); | ||
__exportStar(require("./ed25519"), exports); | ||
__exportStar(require("./multi_ed25519"), exports); | ||
__exportStar(require("./authentication_key"), exports); | ||
//# sourceMappingURL=index.js.map |
import { Deserializer } from './deserializer'; | ||
import { Serializer } from './serializer'; | ||
import { Bytes, Seq } from './types'; | ||
import { AnyNumber, Bytes, Seq } from './types'; | ||
interface Serializable { | ||
@@ -16,4 +16,4 @@ serialize(serializer: Serializer): void; | ||
export declare function bcsToBytes<T extends Serializable>(value: T): Bytes; | ||
export declare function bcsSerializeUint64(value: bigint | number): Bytes; | ||
export declare function bcsSerializeUint64(value: AnyNumber): Bytes; | ||
export {}; | ||
//# sourceMappingURL=helper.d.ts.map |
@@ -1,25 +0,4 @@ | ||
import { Buffer } from 'buffer/'; | ||
import { RawTransaction } from './aptos_types'; | ||
import { Bytes } from './bcs'; | ||
export declare type SigningMessage = Buffer; | ||
export declare type TransactionSignature = Uint8Array; | ||
/** Function that takes in a Signing Message (serialized raw transaction) | ||
* and returns a signature | ||
*/ | ||
export declare type SigningFn = (txn: SigningMessage) => TransactionSignature; | ||
declare class TransactionBuilder<F extends SigningFn> { | ||
private readonly signingFunction; | ||
private readonly publicKey; | ||
constructor(signingFunction: F, publicKey: Uint8Array); | ||
/** Generates a Signing Message out of a raw transaction. */ | ||
static getSigningMessage(rawTxn: RawTransaction): SigningMessage; | ||
private signInternal; | ||
/** Signs a raw transaction and returns a bcs serialized transaction. */ | ||
sign(rawTxn: RawTransaction): Bytes; | ||
} | ||
/** Just a syntatic sugar. | ||
* TODO: add default signing function for Ed25519 */ | ||
export declare class TransactionBuilderEd25519 extends TransactionBuilder<SigningFn> { | ||
} | ||
export {}; | ||
export * from './builder'; | ||
export * as BCS from './bcs'; | ||
export * as TxnBuilderTypes from './aptos_types'; | ||
//# sourceMappingURL=index.d.ts.map |
@@ -18,2 +18,5 @@ "use strict"; | ||
}); | ||
var __exportStar = (this && this.__exportStar) || function(m, exports) { | ||
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); | ||
}; | ||
var __importStar = (this && this.__importStar) || function (mod) { | ||
@@ -27,37 +30,6 @@ if (mod && mod.__esModule) return mod; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.TransactionBuilderEd25519 = void 0; | ||
const SHA3 = __importStar(require("js-sha3")); | ||
const buffer_1 = require("buffer/"); | ||
const aptos_types_1 = require("./aptos_types"); | ||
const bcs_1 = require("./bcs"); | ||
const SALT = 'APTOS::RawTransaction'; | ||
class TransactionBuilder { | ||
constructor(signingFunction, publicKey) { | ||
this.signingFunction = signingFunction; | ||
this.publicKey = publicKey; | ||
} | ||
/** Generates a Signing Message out of a raw transaction. */ | ||
static getSigningMessage(rawTxn) { | ||
const hash = SHA3.sha3_256.create(); | ||
hash.update(buffer_1.Buffer.from(SALT)); | ||
const prefix = new Uint8Array(hash.arrayBuffer()); | ||
return buffer_1.Buffer.from([...prefix, ...(0, bcs_1.bcsToBytes)(rawTxn)]); | ||
} | ||
signInternal(rawTxn) { | ||
const signingMessage = TransactionBuilder.getSigningMessage(rawTxn); | ||
const signatureRaw = this.signingFunction(signingMessage); | ||
const signature = new aptos_types_1.Ed25519Signature(signatureRaw); | ||
const authenticator = new aptos_types_1.TransactionAuthenticatorEd25519(new aptos_types_1.Ed25519PublicKey(this.publicKey), signature); | ||
return new aptos_types_1.SignedTransaction(rawTxn, authenticator); | ||
} | ||
/** Signs a raw transaction and returns a bcs serialized transaction. */ | ||
sign(rawTxn) { | ||
return (0, bcs_1.bcsToBytes)(this.signInternal(rawTxn)); | ||
} | ||
} | ||
/** Just a syntatic sugar. | ||
* TODO: add default signing function for Ed25519 */ | ||
class TransactionBuilderEd25519 extends TransactionBuilder { | ||
} | ||
exports.TransactionBuilderEd25519 = TransactionBuilderEd25519; | ||
exports.TxnBuilderTypes = exports.BCS = void 0; | ||
__exportStar(require("./builder"), exports); | ||
exports.BCS = __importStar(require("./bcs")); | ||
exports.TxnBuilderTypes = __importStar(require("./aptos_types")); | ||
//# sourceMappingURL=index.js.map |
@@ -48,3 +48,3 @@ "use strict"; | ||
const { publicKey } = signingKey; | ||
const txnBuilder = new index_1.TransactionBuilderEd25519((signingMessage) => Nacl.sign(signingMessage, signingKey.secretKey).slice(0, 64), publicKey); | ||
const txnBuilder = new index_1.TransactionBuilderEd25519((signingMessage) => new aptos_types_1.Ed25519Signature(Nacl.sign(signingMessage, signingKey.secretKey).slice(0, 64)), publicKey); | ||
return txnBuilder.sign(rawTxn); | ||
@@ -51,0 +51,0 @@ } |
@@ -57,3 +57,3 @@ { | ||
}, | ||
"version": "1.0.0" | ||
"version": "1.1.0" | ||
} |
@@ -7,5 +7,9 @@ # Aptos TS/JS SDK | ||
You need to connect to an [Aptos](https:/github.com/aptos-labs/aptos-core/) node to use this library, or run one | ||
You need to connect to an [Aptos][repo] node to use this library, or run one | ||
yourself locally. | ||
## API Docs | ||
Docs can be found [here][api-doc] | ||
## Usage | ||
@@ -60,18 +64,13 @@ | ||
## Semantic versioning | ||
This project follows [semver](https://semver.org/) as closely as possible | ||
[examples]: https://github.com/aptos-labs/aptos-core/blob/main/ecosystem/typescript/sdk/examples/ | ||
[repo]: https://github.com/aptos-labs/aptos-core | ||
[npm-image-version]: https://img.shields.io/npm/v/aptos.svg | ||
[npm-image-downloads]: https://img.shields.io/npm/dm/aptos.svg | ||
[npm-url]: https://npmjs.org/package/aptos | ||
[discord-image]: https://img.shields.io/discord/945856774056083548?label=Discord&logo=discord&style=flat~~~~ | ||
[discord-url]: https://discord.gg/aptoslabs | ||
## Semantic versioning | ||
This project follows [semver](https://semver.org/) as closely as possible | ||
[discord-url]: https://discord.gg/aptoslabs | ||
[api-doc]: https://aptos-labs.github.io/ts-sdk-doc/ |
@@ -399,3 +399,3 @@ /* eslint-disable */ | ||
name: string; | ||
visibility: "public" | "script" | "friend"; | ||
visibility: 'public' | 'script' | 'friend'; | ||
generic_type_params: { constraints: MoveAbility[] }[]; | ||
@@ -413,6 +413,6 @@ params: MoveTypeId[]; | ||
export enum MoveAbility { | ||
Copy = "copy", | ||
Drop = "drop", | ||
Store = "store", | ||
Key = "key", | ||
Copy = 'copy', | ||
Drop = 'drop', | ||
Store = 'store', | ||
Key = 'key', | ||
} | ||
@@ -1006,4 +1006,2 @@ | ||
type: string; | ||
/** all public keys of the sender account */ | ||
public_keys: HexEncodedBytes[]; | ||
@@ -1178,1 +1176,37 @@ | ||
} | ||
export interface TokenData { | ||
/** Unique name within this creator's account for this Token's collection */ | ||
collection: string; | ||
/** Description of Token */ | ||
description: string; | ||
/** Name of Token */ | ||
name: string; | ||
/** Optional maximum number of this Token */ | ||
maximum?: number; | ||
/** Total number of this type of Token */ | ||
supply: number; | ||
/** URL for additional information / media */ | ||
uri: string; | ||
} | ||
export interface TokenId { | ||
/** Token creator address */ | ||
creator: string; | ||
/** Unique name within this creator's account for this Token's collection */ | ||
collection: string; | ||
/** Name of Token */ | ||
name: string; | ||
} | ||
export interface Token { | ||
id: TokenId; | ||
value: number; | ||
} |
@@ -13,5 +13,14 @@ import * as Nacl from 'tweetnacl'; | ||
/** | ||
* Class for creating and managing Aptos account | ||
*/ | ||
export class AptosAccount { | ||
/** | ||
* A private key and public key, associated with the given account | ||
*/ | ||
readonly signingKey: Nacl.SignKeyPair; | ||
/** | ||
* Address associated with the given account | ||
*/ | ||
private readonly accountAddress: HexString; | ||
@@ -25,3 +34,10 @@ | ||
/** This class allows passing in an address, to handle account key rotation, where auth_key != public_key */ | ||
/** | ||
* Creates new account instance. Constructor allows passing in an address, | ||
* to handle account key rotation, where auth_key != public_key | ||
* @param privateKeyBytes Private key from which account key pair will be generated. | ||
* If not specified, new key pair is going to be created. | ||
* @param address Account address (e.g. 0xe8012714cd17606cee7188a2a365eef3fe760be598750678c8c5954eb548a591). | ||
* If not specified, a new one will be generated from public key | ||
*/ | ||
constructor(privateKeyBytes?: Uint8Array | undefined, address?: MaybeHexString) { | ||
@@ -36,3 +52,8 @@ if (privateKeyBytes) { | ||
/** Returns the address associated with the given account */ | ||
/** | ||
* This is the key by which Aptos account is referenced. | ||
* It is the 32-byte of the SHA-3 256 cryptographic hash | ||
* of the public key(s) concatenated with a signature scheme identifier byte | ||
* @returns Address associated with the given account | ||
*/ | ||
address(): HexString { | ||
@@ -42,4 +63,8 @@ return this.accountAddress; | ||
/** Returns the authKey for the associated account | ||
* See here for more info: https://aptos.dev/basics/basics-accounts#single-signer-authentication */ | ||
/** | ||
* 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/basics/basics-accounts#single-signer-authentication} | ||
* @returns Authentication key for the associated account | ||
*/ | ||
authKey(): HexString { | ||
@@ -55,3 +80,7 @@ if (!this.authKeyCached) { | ||
/** Returns the public key for the associated account */ | ||
/** | ||
* This key is generated with Ed25519 scheme. | ||
* Public key is used to check a signature of transaction, signed by given account | ||
* @returns The public key for the associated account | ||
*/ | ||
pubKey(): HexString { | ||
@@ -61,2 +90,7 @@ return HexString.ensure(Buffer.from(this.signingKey.publicKey).toString('hex')); | ||
/** | ||
* Signs specified `buffer` with account's private key | ||
* @param buffer A buffer to sign | ||
* @returns A signature HexString | ||
*/ | ||
signBuffer(buffer: Buffer): HexString { | ||
@@ -67,2 +101,7 @@ const signature = Nacl.sign(buffer, this.signingKey.secretKey); | ||
/** | ||
* Signs specified `hexString` with account's private key | ||
* @param hexString A regular string or HexString to sign | ||
* @returns A signature HexString | ||
*/ | ||
signHexString(hexString: MaybeHexString): HexString { | ||
@@ -73,2 +112,15 @@ const toSign = HexString.ensure(hexString).toBuffer(); | ||
/** | ||
* Derives account address, public key and private key | ||
* @returns AptosAccountObject instance. | ||
* @example An example of the returned AptosAccountObject object | ||
* ``` | ||
* { | ||
* address: "0xe8012714cd17606cee7188a2a365eef3fe760be598750678c8c5954eb548a591", | ||
* publicKeyHex: "0xf56d8524faf79fbc0f48c13aeed3b0ce5dd376b4db93b8130a107c0a5e04ba04", | ||
* privateKeyHex: `0x009c9f7c992a06cfafe916f125d8adb7a395fca243e264a8e56a4b3e6accf940 | ||
* d2b11e9ece3049ce60e3c7b4a1c58aebfa9298e29a30a58a67f1998646135204` | ||
* } | ||
* ``` | ||
*/ | ||
toPrivateKeyObject(): AptosAccountObject { | ||
@@ -75,0 +127,0 @@ return { |
@@ -0,1 +1,2 @@ | ||
/* eslint-disable no-bitwise */ | ||
import { AxiosResponse } from 'axios'; | ||
@@ -8,12 +9,3 @@ import { AptosClient, raiseForStatus } from './aptos_client'; | ||
import { AptosAccount } from './aptos_account'; | ||
import { | ||
ChainId, | ||
RawTransaction, | ||
ScriptFunction, | ||
StructTag, | ||
TransactionPayloadScriptFunction, | ||
TypeTagStruct, | ||
AccountAddress, | ||
} from './transaction_builder/aptos_types'; | ||
import { bcsSerializeUint64, bcsToBytes } from './transaction_builder/bcs'; | ||
import { TxnBuilderTypes, TransactionBuilderMultiEd25519, BCS } from './transaction_builder'; | ||
@@ -115,10 +107,10 @@ test('gets genesis account', async () => { | ||
const token = new TypeTagStruct(StructTag.fromString('0x1::TestCoin::TestCoin')); | ||
const token = new TxnBuilderTypes.TypeTagStruct(TxnBuilderTypes.StructTag.fromString('0x1::TestCoin::TestCoin')); | ||
const scriptFunctionPayload = new TransactionPayloadScriptFunction( | ||
ScriptFunction.natual( | ||
const scriptFunctionPayload = new TxnBuilderTypes.TransactionPayloadScriptFunction( | ||
TxnBuilderTypes.ScriptFunction.natual( | ||
'0x1::Coin', | ||
'transfer', | ||
[token], | ||
[bcsToBytes(AccountAddress.fromHex(account2.address())), bcsSerializeUint64(717)], | ||
[BCS.bcsToBytes(TxnBuilderTypes.AccountAddress.fromHex(account2.address())), BCS.bcsSerializeUint64(717)], | ||
), | ||
@@ -132,4 +124,4 @@ ); | ||
const rawTxn = new RawTransaction( | ||
AccountAddress.fromHex(account1.address()), | ||
const rawTxn = new TxnBuilderTypes.RawTransaction( | ||
TxnBuilderTypes.AccountAddress.fromHex(account1.address()), | ||
BigInt(sequnceNumber), | ||
@@ -140,6 +132,6 @@ scriptFunctionPayload, | ||
BigInt(Math.floor(Date.now() / 1000) + 10), | ||
new ChainId(chainId), | ||
new TxnBuilderTypes.ChainId(chainId), | ||
); | ||
const bcsTxn = await AptosClient.generateBCSTransaction(account1, rawTxn); | ||
const bcsTxn = AptosClient.generateBCSTransaction(account1, rawTxn); | ||
const transactionRes = await client.submitSignedBCSTransaction(bcsTxn); | ||
@@ -155,1 +147,88 @@ | ||
); | ||
test( | ||
'submits multisig transaction', | ||
async () => { | ||
const client = new AptosClient(NODE_URL); | ||
const faucetClient = new FaucetClient(NODE_URL, FAUCET_URL, null); | ||
const account1 = new AptosAccount(); | ||
const account2 = new AptosAccount(); | ||
const account3 = new AptosAccount(); | ||
const multiSigPublicKey = new TxnBuilderTypes.MultiEd25519PublicKey( | ||
[ | ||
new TxnBuilderTypes.Ed25519PublicKey(account1.signingKey.publicKey), | ||
new TxnBuilderTypes.Ed25519PublicKey(account2.signingKey.publicKey), | ||
new TxnBuilderTypes.Ed25519PublicKey(account3.signingKey.publicKey), | ||
], | ||
2, | ||
); | ||
const authKey = TxnBuilderTypes.AuthenticationKey.fromMultiEd25519PublicKey(multiSigPublicKey); | ||
const mutisigAccountAddress = authKey.derivedAddress(); | ||
await faucetClient.fundAccount(mutisigAccountAddress, 5000); | ||
let resources = await client.getAccountResources(mutisigAccountAddress); | ||
let accountResource = resources.find((r) => r.type === '0x1::Coin::CoinStore<0x1::TestCoin::TestCoin>'); | ||
expect((accountResource.data as any).coin.value).toBe('5000'); | ||
const account4 = new AptosAccount(); | ||
await faucetClient.fundAccount(account4.address(), 0); | ||
resources = await client.getAccountResources(account4.address()); | ||
accountResource = resources.find((r) => r.type === '0x1::Coin::CoinStore<0x1::TestCoin::TestCoin>'); | ||
expect((accountResource.data as any).coin.value).toBe('0'); | ||
const token = new TxnBuilderTypes.TypeTagStruct(TxnBuilderTypes.StructTag.fromString('0x1::TestCoin::TestCoin')); | ||
const scriptFunctionPayload = new TxnBuilderTypes.TransactionPayloadScriptFunction( | ||
TxnBuilderTypes.ScriptFunction.natual( | ||
'0x1::Coin', | ||
'transfer', | ||
[token], | ||
[BCS.bcsToBytes(TxnBuilderTypes.AccountAddress.fromHex(account4.address())), BCS.bcsSerializeUint64(123)], | ||
), | ||
); | ||
const [{ sequence_number: sequnceNumber }, chainId] = await Promise.all([ | ||
client.getAccount(mutisigAccountAddress), | ||
client.getChainId(), | ||
]); | ||
const rawTxn = new TxnBuilderTypes.RawTransaction( | ||
TxnBuilderTypes.AccountAddress.fromHex(mutisigAccountAddress), | ||
BigInt(sequnceNumber), | ||
scriptFunctionPayload, | ||
1000n, | ||
1n, | ||
BigInt(Math.floor(Date.now() / 1000) + 10), | ||
new TxnBuilderTypes.ChainId(chainId), | ||
); | ||
const txnBuilder = new TransactionBuilderMultiEd25519((signingMessage: TxnBuilderTypes.SigningMessage) => { | ||
const sigHexStr1 = account1.signBuffer(signingMessage); | ||
const sigHexStr3 = account3.signBuffer(signingMessage); | ||
const bitmap = TxnBuilderTypes.MultiEd25519Signature.createBitmap([0, 2]); | ||
const muliEd25519Sig = new TxnBuilderTypes.MultiEd25519Signature( | ||
[ | ||
new TxnBuilderTypes.Ed25519Signature(sigHexStr1.toUint8Array()), | ||
new TxnBuilderTypes.Ed25519Signature(sigHexStr3.toUint8Array()), | ||
], | ||
bitmap, | ||
); | ||
return muliEd25519Sig; | ||
}, multiSigPublicKey); | ||
const bcsTxn = txnBuilder.sign(rawTxn); | ||
const transactionRes = await client.submitSignedBCSTransaction(bcsTxn); | ||
await client.waitForTransaction(transactionRes.hash); | ||
resources = await client.getAccountResources(account4.address()); | ||
accountResource = resources.find((r) => r.type === '0x1::Coin::CoinStore<0x1::TestCoin::TestCoin>'); | ||
expect((accountResource.data as any).coin.value).toBe('123'); | ||
}, | ||
30 * 1000, | ||
); |
@@ -12,4 +12,3 @@ import { AxiosRequestConfig, AxiosResponse } from 'axios'; | ||
import { AptosError } from './api/data-contracts'; | ||
import * as TxnBuilderTypes from './transaction_builder/aptos_types'; | ||
import { SigningMessage, TransactionBuilderEd25519 } from './transaction_builder'; | ||
import { TxnBuilderTypes, TransactionBuilderEd25519 } from './transaction_builder'; | ||
@@ -46,2 +45,6 @@ export class RequestError extends Error { | ||
/** | ||
* Provides methods for retrieving data from Aptos node. | ||
* For more detailed API specification see {@link https://fullnode.devnet.aptoslabs.com/spec.html#/} | ||
*/ | ||
export class AptosClient { | ||
@@ -61,2 +64,8 @@ nodeUrl: string; | ||
/** | ||
* Establishes a connection to Aptos node | ||
* @param nodeUrl A url of the Aptos Node API endpoint | ||
* @param config An optional config for inner axios instance. | ||
* Detailed `config` description: {@link https://github.com/axios/axios#request-config} | ||
*/ | ||
constructor(nodeUrl: string, config?: AptosClientConfig) { | ||
@@ -80,3 +89,14 @@ this.nodeUrl = nodeUrl; | ||
/** Returns the sequence number and authentication key for an account */ | ||
/** | ||
* Queries an Aptos account by address | ||
* @param accountAddress Hex-encoded 16 bytes Aptos account address | ||
* @returns Core account resource, used for identifying account and transaction execution | ||
* @example An example of the returned account | ||
* ``` | ||
* { | ||
* sequence_number: "1", | ||
* authentication_key: "0x5307b5f4bc67829097a8ba9b43dba3b88261eeccd1f709d9bde240fc100fbb69" | ||
* } | ||
* ``` | ||
*/ | ||
async getAccount(accountAddress: MaybeHexString): Promise<Types.Account> { | ||
@@ -88,3 +108,10 @@ const response = await this.accounts.getAccount(HexString.ensure(accountAddress).hex()); | ||
/** Returns transactions sent by the account */ | ||
/** | ||
* Queries transactions sent by given account | ||
* @param accountAddress Hex-encoded 16 bytes Aptos account address | ||
* @param query Optional pagination object | ||
* @param query.start The start transaction version of the page. Default is the latest ledger version | ||
* @param query.limit The max number of transactions should be returned for the page. Default is 25. | ||
* @returns An array of on-chain transactions, sent by account | ||
*/ | ||
async getAccountTransactions( | ||
@@ -99,3 +126,10 @@ accountAddress: MaybeHexString, | ||
/** Returns all modules associated with the account */ | ||
/** | ||
* Queries modules associated with given account | ||
* @param accountAddress Hex-encoded 16 bytes Aptos account address | ||
* @param query.version Specifies ledger version of transactions. By default latest version will be used | ||
* @returns Account modules array for a specific ledger version. | ||
* Module is represented by MoveModule interface. It contains module `bytecode` and `abi`, | ||
* which is JSON representation of a module | ||
*/ | ||
async getAccountModules( | ||
@@ -110,3 +144,11 @@ accountAddress: MaybeHexString, | ||
/** Returns the module identified by address and module name */ | ||
/** | ||
* Queries module associated with given account by module name | ||
* @param accountAddress Hex-encoded 16 bytes Aptos account address | ||
* @param moduleName The name of the module | ||
* @param query.version Specifies ledger version of transactions. By default latest version will be used | ||
* @returns Specified module. | ||
* Module is represented by MoveModule interface. It contains module `bytecode` and `abi`, | ||
* which JSON representation of a module | ||
*/ | ||
async getAccountModule( | ||
@@ -122,3 +164,15 @@ accountAddress: MaybeHexString, | ||
/** Returns all resources associated with the account */ | ||
/** | ||
* Queries all resources associated with given account | ||
* @param accountAddress Hex-encoded 16 bytes Aptos account address | ||
* @param query.version Specifies ledger version of transactions. By default latest version will be used | ||
* @returns Account resources for a specific ledger version | ||
* @example An example of an account resource | ||
* ``` | ||
* { | ||
* type: "0x1::AptosAccount::Coin", | ||
* data: { value: 6 } | ||
* } | ||
* ``` | ||
*/ | ||
async getAccountResources( | ||
@@ -133,3 +187,16 @@ accountAddress: MaybeHexString, | ||
/** Returns the resource by the address and resource type */ | ||
/** | ||
* Queries resource associated with given account by resource type | ||
* @param accountAddress Hex-encoded 16 bytes Aptos account address | ||
* @param resourceType String representation of an on-chain Move struct type | ||
* @param query.version Specifies ledger version of transactions. By default latest version will be used | ||
* @returns Account resource of specified type and ledger version | ||
* @example An example of an account resource | ||
* ``` | ||
* { | ||
* type: "0x1::AptosAccount::Coin", | ||
* data: { value: 6 } | ||
* } | ||
* ``` | ||
*/ | ||
async getAccountResource( | ||
@@ -150,18 +217,31 @@ accountAddress: MaybeHexString, | ||
/** Generates a signed transaction that can be submitted to the chain for execution. */ | ||
static async generateBCSTransaction( | ||
accountFrom: AptosAccount, | ||
rawTxn: TxnBuilderTypes.RawTransaction, | ||
): Promise<Uint8Array> { | ||
const txnBuilder = new TransactionBuilderEd25519((signingMessage: SigningMessage) => { | ||
static generateBCSTransaction(accountFrom: AptosAccount, rawTxn: TxnBuilderTypes.RawTransaction): Uint8Array { | ||
const txnBuilder = new TransactionBuilderEd25519((signingMessage: TxnBuilderTypes.SigningMessage) => { | ||
// @ts-ignore | ||
const sigHexStr = accountFrom.signBuffer(signingMessage); | ||
return sigHexStr.toUint8Array(); | ||
return new TxnBuilderTypes.Ed25519Signature(sigHexStr.toUint8Array()); | ||
}, accountFrom.pubKey().toUint8Array()); | ||
const signedTxn = await txnBuilder.sign(rawTxn); | ||
return signedTxn; | ||
return txnBuilder.sign(rawTxn); | ||
} | ||
/** Generates a transaction request that can be submitted to produce a raw transaction that | ||
* can be signed, which upon being signed can be submitted to the blockchain. */ | ||
* can be signed, which upon being signed can be submitted to the blockchain | ||
* @param sender Hex-encoded 16 bytes Aptos account address of transaction sender | ||
* @param payload Transaction payload. It depends on transaction type you want to send | ||
* @param options Options allow to overwrite default transaction options. | ||
* Defaults are: | ||
* ```bash | ||
* { | ||
* sender: senderAddress.hex(), | ||
* sequence_number: account.sequence_number, | ||
* max_gas_amount: "1000", | ||
* gas_unit_price: "1", | ||
* gas_currency_code: "XUS", | ||
* // Unix timestamp, in seconds + 10 seconds | ||
* expiration_timestamp_secs: (Math.floor(Date.now() / 1000) + 10).toString(), | ||
* } | ||
* ``` | ||
* @returns A transaction object | ||
*/ | ||
async generateTransaction( | ||
@@ -187,5 +267,9 @@ sender: MaybeHexString, | ||
/** Converts a transaction request by `generate_transaction` into it's binary hex BCS representation, ready for | ||
/** | ||
* Converts a transaction request by `generate_transaction` into it's binary hex BCS representation, ready for | ||
* signing and submitting. | ||
* Generally you may want to use `signTransaction`, as it takes care of this step + signing */ | ||
* Generally you may want to use `signTransaction`, as it takes care of this step + signing | ||
* @param txnRequest A raw transaction generated by `generateTransaction` method | ||
* @returns A hex-encoded string prefixed with `0x` and fulfilled with two hex digits per byte | ||
*/ | ||
async createSigningMessage(txnRequest: Types.UserTransactionRequest): Promise<Types.HexEncodedBytes> { | ||
@@ -200,3 +284,7 @@ const response = await this.transactions.createSigningMessage(txnRequest); | ||
/** Converts a transaction request produced by `generate_transaction` into a properly signed | ||
* transaction, which can then be submitted to the blockchain. */ | ||
* transaction, which can then be submitted to the blockchain | ||
* @param accountFrom AptosAccount of transaction sender | ||
* @param txnRequest A raw transaction generated by `generateTransaction` method | ||
* @returns A transaction, signed with sender account | ||
*/ | ||
async signTransaction( | ||
@@ -218,2 +306,8 @@ accountFrom: AptosAccount, | ||
/** | ||
* Queries events by event key | ||
* @param eventKey Event key for an event stream. It is BCS serialized bytes | ||
* of `guid` field in the Move struct `EventHandle` | ||
* @returns Array of events assotiated with given key | ||
*/ | ||
async getEventsByEventKey(eventKey: Types.HexEncodedBytes): Promise<Types.Event[]> { | ||
@@ -225,2 +319,15 @@ const response = await this.events.getEventsByEventKey(eventKey); | ||
/** | ||
* Extracts event key from the account resource identified by the | ||
* `event_handle_struct` and `field_name`, then returns events identified by the event key | ||
* @param address Hex-encoded 16 bytes Aptos account from which events are queried | ||
* @param eventHandleStruct String representation of an on-chain Move struct type. | ||
* (e.g. `0x1::Coin::CoinStore<0x1::TestCoin::TestCoin>`) | ||
* @param fieldName The field name of the EventHandle in the struct | ||
* @param query Optional query object | ||
* @param query.start The start sequence number in the EVENT STREAM, defaulting to the latest event. | ||
* The events are returned in the reverse order of sequence number | ||
* @param query.limit The number of events to be returned for the page default is 5 | ||
* @returns Array of events | ||
*/ | ||
async getEventsByEventHandle( | ||
@@ -242,3 +349,7 @@ address: MaybeHexString, | ||
/** Submits a signed transaction to the transaction endpoint that takes JSON payload. */ | ||
/** | ||
* Submits a signed transaction to the transaction endpoint that takes JSON payload | ||
* @param signedTxnRequest A transaction, signed by `signTransaction` method | ||
* @returns Transaction that is accepted and submitted to mempool | ||
*/ | ||
async submitTransaction(signedTxnRequest: Types.SubmitTransactionRequest): Promise<Types.PendingTransaction> { | ||
@@ -250,3 +361,7 @@ const response = await this.transactions.submitTransaction(signedTxnRequest); | ||
/** Submits a signed transaction to the the endpoint that takes BCS payload. */ | ||
/** | ||
* Submits a signed transaction to the the endpoint that takes BCS payload | ||
* @param signedTxn A BCS transaction representation | ||
* @returns Transaction that is accepted and submitted to mempool | ||
*/ | ||
async submitSignedBCSTransaction(signedTxn: Uint8Array): Promise<Types.PendingTransaction> { | ||
@@ -269,2 +384,9 @@ // Need to construct a customized post request for transactions in BCS payload | ||
/** | ||
* Queries on-chain transactions | ||
* @param query Optional pagination object | ||
* @param query.start The start transaction version of the page. Default is the latest ledger version | ||
* @param query.limit The max number of transactions should be returned for the page. Default is 25 | ||
* @returns Array of on-chain transactions | ||
*/ | ||
async getTransactions(query?: { start?: number; limit?: number }): Promise<Types.OnChainTransaction[]> { | ||
@@ -276,2 +398,11 @@ const response = await this.transactions.getTransactions(query); | ||
/** | ||
* Queries transaction by hash or version. When given transaction hash, server first looks up | ||
* on-chain transaction by hash; if no on-chain transaction found, then look up transaction | ||
* by hash in the mempool (pending) transactions. | ||
* When given a transaction version, server looks up the transaction on-chain by version | ||
* @param txnHashOrVersion - Transaction hash should be hex-encoded bytes string with 0x prefix. | ||
* Transaction version is an uint64 number. | ||
* @returns Transaction from mempool or on-chain transaction | ||
*/ | ||
async getTransaction(txnHashOrVersion: string): Promise<Types.Transaction> { | ||
@@ -283,2 +414,14 @@ const response = await this.transactions.getTransaction(txnHashOrVersion); | ||
/** | ||
* Defines if specified transaction is currently in pending state | ||
* @param txnHash A hash of transaction | ||
* | ||
* To create a transaction hash: | ||
* | ||
* 1. Create hash message bytes: "Aptos::Transaction" bytes + BCS bytes of Transaction. | ||
* 2. Apply hash algorithm SHA3-256 to the hash message bytes. | ||
* 3. Hex-encode the hash bytes with 0x prefix. | ||
* | ||
* @returns `true` if transaction is in pending state and `false` otherwise | ||
*/ | ||
async transactionPending(txnHash: Types.HexEncodedBytes): Promise<boolean> { | ||
@@ -294,3 +437,15 @@ const response = await this.transactions.getTransaction(txnHash); | ||
/** Waits up to 10 seconds for a transaction to move past pending state */ | ||
/** | ||
* Waits up to 10 seconds for a transaction to move past pending state | ||
* @param txnHash A hash of transaction | ||
* @returns A Promise, that will resolve if transaction is accepted to the blockchain, | ||
* and reject if more then 10 seconds passed | ||
* @example | ||
* ``` | ||
* const signedTxn = await this.aptosClient.signTransaction(account, txnRequest); | ||
* const res = await this.aptosClient.submitTransaction(signedTxn); | ||
* await this.aptosClient.waitForTransaction(res.hash); | ||
* // do smth after transaction is accepted into blockchain | ||
* ``` | ||
*/ | ||
async waitForTransaction(txnHash: Types.HexEncodedBytes) { | ||
@@ -309,2 +464,16 @@ let count = 0; | ||
/** | ||
* Queries the latest ledger information | ||
* @param params Request params | ||
* @returns Latest ledger information | ||
* @example Example of returned data | ||
* ``` | ||
* { | ||
* chain_id: 15, | ||
* epoch: 6, | ||
* ledger_version: "2235883", | ||
* ledger_timestamp:"1654580922321826" | ||
* } | ||
* ``` | ||
*/ | ||
async getLedgerInfo(params: RequestParams = {}): Promise<Types.LedgerInfo> { | ||
@@ -320,2 +489,6 @@ const result = await this.client.request<Types.LedgerInfo, AptosError>({ | ||
/** | ||
* @param params Request params | ||
* @returns Current chain id | ||
*/ | ||
async getChainId(params: RequestParams = {}): Promise<number> { | ||
@@ -326,2 +499,13 @@ const result = await this.getLedgerInfo(params); | ||
/** | ||
* Gets a table item for a table identified by the handle and the key for the item. | ||
* Key and value types need to be passed in to help with key serialization and value deserialization. | ||
* @param handle A pointer to where that table is stored | ||
* @param data Object, that describes table item | ||
* @param data.key_type Move type of table key (e.g. `vector<u8>`) | ||
* @param data.value_type Move type of table value (e.g. `u64`) | ||
* @param data.key Value of table key | ||
* @param params Request params | ||
* @returns Table item value rendered in JSON | ||
*/ | ||
async getTableItem(handle: string, data: Types.TableItemRequest, params?: RequestParams): Promise<any> { | ||
@@ -328,0 +512,0 @@ const tableItem = await this.tables.getTableItem(handle, data, params); |
@@ -7,5 +7,15 @@ /** Faucet creates and funds accounts. This is a thin wrapper around that. */ | ||
/** | ||
* Class for requsting tokens from faucet | ||
*/ | ||
export class FaucetClient extends AptosClient { | ||
faucetUrl: string; | ||
/** | ||
* Establishes a connection to Aptos node | ||
* @param nodeUrl A url of the Aptos Node API endpoint | ||
* @param faucetUrl A faucet url | ||
* @param config An optional config for inner axios instance | ||
* Detailed config description: {@link https://github.com/axios/axios#request-config} | ||
*/ | ||
constructor(nodeUrl: string, faucetUrl: string, config?: AptosClientConfig) { | ||
@@ -16,4 +26,9 @@ super(nodeUrl, config); | ||
/** This creates an account if it does not exist and mints the specified amount of | ||
coins into that account */ | ||
/** | ||
* This creates an account if it does not exist and mints the specified amount of | ||
* coins into that account | ||
* @param address Hex-encoded 16 bytes Aptos account address wich mints tokens | ||
* @param amount Amount of tokens to mint | ||
* @returns Hashes of submitted transactions | ||
*/ | ||
async fundAccount(address: MaybeHexString, amount: number): Promise<Types.HexEncodedBytes[]> { | ||
@@ -20,0 +35,0 @@ const url = `${this.faucetUrl}/mint?amount=${amount}&address=${HexString.ensure(address).noPrefix()}`; |
@@ -7,2 +7,6 @@ import { Buffer } from 'buffer/'; // the trailing slash is important! | ||
/** | ||
* A util class for working with hex strings. | ||
* Hex strings are strings that are prefixed with `0x` | ||
*/ | ||
export class HexString { | ||
@@ -12,2 +16,7 @@ /// We want to make sure this hexString has the `0x` hex prefix | ||
/** | ||
* Creates new hex string from Buffer | ||
* @param buffer A buffer to convert | ||
* @returns New HexString | ||
*/ | ||
static fromBuffer(buffer: Buffer): HexString { | ||
@@ -17,2 +26,7 @@ return new HexString(buffer.toString('hex')); | ||
/** | ||
* Creates new hex string from Uint8Array | ||
* @param arr Uint8Array to convert | ||
* @returns New HexString | ||
*/ | ||
static fromUint8Array(arr: Uint8Array): HexString { | ||
@@ -22,2 +36,14 @@ return HexString.fromBuffer(Buffer.from(arr)); | ||
/** | ||
* Ensures `hexString` is instance of `HexString` class | ||
* @param hexString String to check | ||
* @returns New HexString if `hexString` is regular string or `hexString` if it is HexString instance | ||
* @example | ||
* ``` | ||
* const regularString = "string"; | ||
* const hexString = new HexString("string"); // "0xstring" | ||
* HexString.ensure(regularString); // "0xstring" | ||
* HexString.ensure(hexString); // "0xstring" | ||
* ``` | ||
*/ | ||
static ensure(hexString: MaybeHexString): HexString { | ||
@@ -30,2 +56,12 @@ if (typeof hexString === 'string') { | ||
/** | ||
* Creates new HexString instance from regular string. If specified string already starts with "0x" prefix, | ||
* it will not add another one | ||
* @param hexString String to convert | ||
* @example | ||
* ``` | ||
* const string = "string"; | ||
* new HexString(string); // "0xstring" | ||
* ``` | ||
*/ | ||
constructor(hexString: string | Types.HexEncodedBytes) { | ||
@@ -39,2 +75,6 @@ if (hexString.startsWith('0x')) { | ||
/** | ||
* Getter for inner hexString | ||
* @returns Inner hex string | ||
*/ | ||
hex(): string { | ||
@@ -44,2 +84,11 @@ return this.hexString; | ||
/** | ||
* Getter for inner hexString without prefix | ||
* @returns Inner hex string without prefix | ||
* @example | ||
* ``` | ||
* const hexString = new HexString("string"); // "0xstring" | ||
* hexString.noPrefix(); // "string" | ||
* ``` | ||
*/ | ||
noPrefix(): string { | ||
@@ -49,2 +98,6 @@ return this.hexString.slice(2); | ||
/** | ||
* Overrides default `toString` method | ||
* @returns Inner hex string | ||
*/ | ||
toString(): string { | ||
@@ -54,2 +107,10 @@ return this.hex(); | ||
/** | ||
* Trimmes extra zeroes in the begining of a string | ||
* @returns Inner hexString without leading zeroes | ||
* @example | ||
* ``` | ||
* new HexString("0x000000string").toShortString(); // result = "0xstring" | ||
* ``` | ||
*/ | ||
toShortString(): string { | ||
@@ -60,2 +121,6 @@ const trimmed = this.hexString.replace(/^0x0*/, ''); | ||
/** | ||
* Converts hex string to a Buffer in hex encoding | ||
* @returns Buffer from inner hexString without prefix | ||
*/ | ||
toBuffer(): Buffer { | ||
@@ -65,2 +130,6 @@ return Buffer.from(this.noPrefix(), 'hex'); | ||
/** | ||
* Converts hex string to a Uint8Array | ||
* @returns Uint8Array from inner hexString without prefix | ||
*/ | ||
toUint8Array(): Uint8Array { | ||
@@ -67,0 +136,0 @@ return Uint8Array.from(this.toBuffer()); |
@@ -8,1 +8,2 @@ // All parts of our package are accessible as imports, but we re-export our higher level API here for convenience | ||
export * from './types'; | ||
export * from './transaction_builder'; |
@@ -6,5 +6,12 @@ import { AptosAccount } from './aptos_account'; | ||
/** | ||
* Class for creating, minting and managing minting NFT collections and tokens | ||
*/ | ||
export class TokenClient { | ||
aptosClient: AptosClient; | ||
/** | ||
* Creates new TokenClient instance | ||
* @param aptosClient AptosClient instance | ||
*/ | ||
constructor(aptosClient: AptosClient) { | ||
@@ -14,2 +21,8 @@ this.aptosClient = aptosClient; | ||
/** | ||
* Brings together methods for generating, signing and submitting transaction | ||
* @param account AptosAccount which will sign a transaction | ||
* @param payload Transaction payload. It depends on transaction type you want to send | ||
* @returns Promise that resolves to transaction hash | ||
*/ | ||
async submitTransactionHelper(account: AptosAccount, payload: Types.TransactionPayload) { | ||
@@ -25,3 +38,10 @@ const txnRequest = await this.aptosClient.generateTransaction(account.address(), payload, { | ||
// Creates a new collection within the specified account | ||
/** | ||
* Creates a new NFT collection within the specified account | ||
* @param account AptosAccount where collection will be created | ||
* @param name Collection name | ||
* @param description Collection description | ||
* @param uri URL to additional info about collection | ||
* @returns A hash of transaction | ||
*/ | ||
async createCollection( | ||
@@ -47,3 +67,12 @@ account: AptosAccount, | ||
// Creates a new token within the specified account | ||
/** | ||
* Creates a new NFT within the specified account | ||
* @param account AptosAccount where token will be created | ||
* @param collectionName Name of collection, that token belongs to | ||
* @param name Token name | ||
* @param description Token description | ||
* @param supply Token supply | ||
* @param uri URL to additional info about token | ||
* @returns A hash of transaction | ||
*/ | ||
async createToken( | ||
@@ -74,3 +103,12 @@ account: AptosAccount, | ||
// Offer token to another account | ||
/** | ||
* Transfers specified amount of tokens from account to receiver | ||
* @param account AptosAccount where token from which tokens will be transfered | ||
* @param receiver Hex-encoded 16 bytes Aptos account address to which tokens will be transfered | ||
* @param creator Hex-encoded 16 bytes Aptos account address to which created tokens | ||
* @param collectionName Name of collection where token is stored | ||
* @param name Token name | ||
* @param amount Amount of tokens which will be transfered | ||
* @returns A hash of transaction | ||
*/ | ||
async offerToken( | ||
@@ -100,3 +138,11 @@ account: AptosAccount, | ||
// Claim token | ||
/** | ||
* Claims a token on specified account | ||
* @param account AptosAccount which will claim token | ||
* @param sender Hex-encoded 16 bytes Aptos account address which holds a token | ||
* @param creator Hex-encoded 16 bytes Aptos account address which created a token | ||
* @param collectionName Name of collection where token is stored | ||
* @param name Token name | ||
* @returns A hash of transaction | ||
*/ | ||
async claimToken( | ||
@@ -119,3 +165,11 @@ account: AptosAccount, | ||
// Cancel token | ||
/** | ||
* Removes a token from pending claims list | ||
* @param account AptosAccount which will remove token from pending list | ||
* @param receiver Hex-encoded 16 bytes Aptos account address which had to claim token | ||
* @param creator Hex-encoded 16 bytes Aptos account address which created a token | ||
* @param collectionName Name of collection where token is strored | ||
* @param name Token name | ||
* @returns A hash of transaction | ||
*/ | ||
async cancelTokenOffer( | ||
@@ -138,2 +192,22 @@ account: AptosAccount, | ||
/** | ||
* Queries collection data | ||
* @param creator Hex-encoded 16 bytes Aptos account address which created a collection | ||
* @param collectionName Collection name | ||
* @returns Collection data in below format | ||
* ``` | ||
* Collection { | ||
* // Describes the collection | ||
* description: string, | ||
* // Unique name within this creators account for this collection | ||
* name: string, | ||
* // URL for additional information/media | ||
* uri: string, | ||
* // Total number of distinct Tokens tracked by the collection | ||
* count: number, | ||
* // Optional maximum number of tokens allowed within this collections | ||
* maximum: number | ||
* } | ||
* ``` | ||
*/ | ||
async getCollectionData(creator: MaybeHexString, collectionName: string): Promise<any> { | ||
@@ -153,4 +227,26 @@ const resources = await this.aptosClient.getAccountResources(creator); | ||
// Retrieve the token's creation_num, which is useful for non-creator operations | ||
async getTokenData(creator: MaybeHexString, collectionName: string, tokenName: string): Promise<number> { | ||
/** | ||
* Queries token data from collection | ||
* @param creator Hex-encoded 16 bytes Aptos account address which created a token | ||
* @param collectionName Name of collection, which holds a token | ||
* @param tokenName Token name | ||
* @returns Token data in below format | ||
* ``` | ||
* TokenData { | ||
* // Unique name within this creators account for this Token's collection | ||
* collection: string; | ||
* // Describes this Token | ||
* description: string; | ||
* // The name of this Token | ||
* name: string; | ||
* // Optional maximum number of this type of Token. | ||
* maximum: number; | ||
* // Total number of this type of Token | ||
* supply: number; | ||
* /// URL for additional information / media | ||
* uri: string; | ||
* } | ||
* ``` | ||
*/ | ||
async getTokenData(creator: MaybeHexString, collectionName: string, tokenName: string): Promise<Types.TokenData> { | ||
const collection: { type: string; data: any } = await this.aptosClient.getAccountResource( | ||
@@ -177,4 +273,16 @@ creator, | ||
// Retrieve the token's creation_num, which is useful for non-creator operations | ||
async getTokenBalance(creator: MaybeHexString, collectionName: string, tokenName: string): Promise<number> { | ||
/** | ||
* Queries specific token from account's TokenStore | ||
* @param creator Hex-encoded 16 bytes Aptos account address which created a token | ||
* @param collectionName Name of collection, which holds a token | ||
* @param tokenName Token name | ||
* @returns Token object in below format | ||
* ``` | ||
* Token { | ||
* id: TokenId; | ||
* value: number; | ||
* } | ||
* ``` | ||
*/ | ||
async getTokenBalance(creator: MaybeHexString, collectionName: string, tokenName: string): Promise<Types.Token> { | ||
const tokenStore: { type: string; data: any } = await this.aptosClient.getAccountResource( | ||
@@ -181,0 +289,0 @@ creator, |
/* eslint-disable @typescript-eslint/naming-convention */ | ||
/* eslint-disable max-classes-per-file */ | ||
import { Serializer, Deserializer, Bytes, Seq, deserializeVector, serializeVector } from '../bcs'; | ||
import { Serializer, Deserializer, Seq, deserializeVector, serializeVector } from '../bcs'; | ||
import { AccountAddress } from './account_address'; | ||
import { Ed25519PublicKey, Ed25519Signature } from './ed25519'; | ||
import { MultiEd25519PublicKey, MultiEd25519Signature } from './multi_ed25519'; | ||
@@ -54,30 +55,5 @@ export abstract class TransactionAuthenticator { | ||
* | ||
* @param public_key BCS bytes for a list of public keys. | ||
* @param public_key | ||
* @param signature | ||
* | ||
* @example | ||
* Developers must manually construct the input to get the BCS bytes. | ||
* See below code example for the BCS input. | ||
* ```ts | ||
* interface MultiEd25519PublicKey { | ||
* // A list of public keys | ||
* public_keys: Uint8Array[], | ||
* // At least `threshold` signatures must be valid | ||
* threshold: Uint8, | ||
* } | ||
* ``` | ||
* @param signature BCS bytes of multiple signatures. | ||
* | ||
* @example | ||
* Developers must manually construct the input to get the BCS bytes. | ||
* See below code example for the BCS input. | ||
* ```ts | ||
* interface MultiEd25519Signature { | ||
* // A list of signatures | ||
* signatures: Uint8Array[], | ||
* // 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. | ||
* bitmap: Uint8Array, | ||
* } | ||
* ``` | ||
*/ | ||
@@ -176,53 +152,1 @@ constructor(public readonly public_key: MultiEd25519PublicKey, public readonly signature: MultiEd25519Signature) { | ||
} | ||
export class Ed25519PublicKey { | ||
constructor(public readonly value: Bytes) {} | ||
serialize(serializer: Serializer): void { | ||
serializer.serializeBytes(this.value); | ||
} | ||
static deserialize(deserializer: Deserializer): Ed25519PublicKey { | ||
const value = deserializer.deserializeBytes(); | ||
return new Ed25519PublicKey(value); | ||
} | ||
} | ||
export class Ed25519Signature { | ||
constructor(public readonly value: Bytes) {} | ||
serialize(serializer: Serializer): void { | ||
serializer.serializeBytes(this.value); | ||
} | ||
static deserialize(deserializer: Deserializer): Ed25519Signature { | ||
const value = deserializer.deserializeBytes(); | ||
return new Ed25519Signature(value); | ||
} | ||
} | ||
export class MultiEd25519PublicKey { | ||
constructor(public readonly value: Bytes) {} | ||
serialize(serializer: Serializer): void { | ||
serializer.serializeBytes(this.value); | ||
} | ||
static deserialize(deserializer: Deserializer): MultiEd25519PublicKey { | ||
const value = deserializer.deserializeBytes(); | ||
return new MultiEd25519PublicKey(value); | ||
} | ||
} | ||
export class MultiEd25519Signature { | ||
constructor(public readonly value: Bytes) {} | ||
serialize(serializer: Serializer): void { | ||
serializer.serializeBytes(this.value); | ||
} | ||
static deserialize(deserializer: Deserializer): MultiEd25519Signature { | ||
const value = deserializer.deserializeBytes(); | ||
return new MultiEd25519Signature(value); | ||
} | ||
} |
@@ -0,1 +1,3 @@ | ||
import { Buffer } from 'buffer/'; | ||
export * from './account_address'; | ||
@@ -6,1 +8,6 @@ export * from './authenticator'; | ||
export * from './identifier'; | ||
export * from './ed25519'; | ||
export * from './multi_ed25519'; | ||
export * from './authentication_key'; | ||
export type SigningMessage = Buffer; |
import { Deserializer } from './deserializer'; | ||
import { Serializer } from './serializer'; | ||
import { Bytes, Seq } from './types'; | ||
import { AnyNumber, Bytes, Seq } from './types'; | ||
@@ -37,3 +37,3 @@ interface Serializable { | ||
export function bcsSerializeUint64(value: bigint | number): Bytes { | ||
export function bcsSerializeUint64(value: AnyNumber): Bytes { | ||
const serializer = new Serializer(); | ||
@@ -40,0 +40,0 @@ serializer.serializeU64(value); |
@@ -1,61 +0,3 @@ | ||
import * as SHA3 from 'js-sha3'; | ||
import { Buffer } from 'buffer/'; | ||
import { | ||
Ed25519PublicKey, | ||
Ed25519Signature, | ||
RawTransaction, | ||
SignedTransaction, | ||
TransactionAuthenticatorEd25519, | ||
} from './aptos_types'; | ||
import { bcsToBytes, Bytes } from './bcs'; | ||
const SALT = 'APTOS::RawTransaction'; | ||
export type SigningMessage = Buffer; | ||
export type TransactionSignature = Uint8Array; | ||
/** Function that takes in a Signing Message (serialized raw transaction) | ||
* and returns a signature | ||
*/ | ||
export type SigningFn = (txn: SigningMessage) => TransactionSignature; | ||
class TransactionBuilder<F extends SigningFn> { | ||
private readonly signingFunction: F; | ||
private readonly publicKey: Uint8Array; | ||
constructor(signingFunction: F, publicKey: Uint8Array) { | ||
this.signingFunction = signingFunction; | ||
this.publicKey = publicKey; | ||
} | ||
/** Generates a Signing Message out of a raw transaction. */ | ||
static getSigningMessage(rawTxn: RawTransaction): SigningMessage { | ||
const hash = SHA3.sha3_256.create(); | ||
hash.update(Buffer.from(SALT)); | ||
const prefix = new Uint8Array(hash.arrayBuffer()); | ||
return Buffer.from([...prefix, ...bcsToBytes(rawTxn)]); | ||
} | ||
private signInternal(rawTxn: RawTransaction): SignedTransaction { | ||
const signingMessage = TransactionBuilder.getSigningMessage(rawTxn); | ||
const signatureRaw = this.signingFunction(signingMessage); | ||
const signature = new Ed25519Signature(signatureRaw); | ||
const authenticator = new TransactionAuthenticatorEd25519(new Ed25519PublicKey(this.publicKey), signature); | ||
return new SignedTransaction(rawTxn, authenticator); | ||
} | ||
/** Signs a raw transaction and returns a bcs serialized transaction. */ | ||
sign(rawTxn: RawTransaction): Bytes { | ||
return bcsToBytes(this.signInternal(rawTxn)); | ||
} | ||
} | ||
/** Just a syntatic sugar. | ||
* TODO: add default signing function for Ed25519 */ | ||
export class TransactionBuilderEd25519 extends TransactionBuilder<SigningFn> {} | ||
export * from './builder'; | ||
export * as BCS from './bcs'; | ||
export * as TxnBuilderTypes from './aptos_types'; |
@@ -10,2 +10,3 @@ /* eslint-disable max-len */ | ||
ChainId, | ||
Ed25519Signature, | ||
Module, | ||
@@ -47,3 +48,3 @@ ModuleBundle, | ||
const txnBuilder = new TransactionBuilderEd25519( | ||
(signingMessage) => Nacl.sign(signingMessage, signingKey.secretKey).slice(0, 64), | ||
(signingMessage) => new Ed25519Signature(Nacl.sign(signingMessage, signingKey.secretKey).slice(0, 64)), | ||
publicKey, | ||
@@ -50,0 +51,0 @@ ); |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
648909
245
11648
75