Comparing version 0.0.20 to 1.0.0
@@ -7,21 +7,26 @@ module.exports = { | ||
}, | ||
extends: ["airbnb-base"], | ||
parser: "@typescript-eslint/parser", | ||
ignorePatterns: ['*.js', 'examples/*'], | ||
extends: ['airbnb-base', 'airbnb-typescript/base'], | ||
parser: '@typescript-eslint/parser', | ||
parserOptions: { | ||
ecmaVersion: "latest", | ||
sourceType: "module", | ||
tsconfigRootDir: __dirname, | ||
project: ['tsconfig.json'], | ||
ecmaVersion: 'latest', | ||
sourceType: 'module', | ||
}, | ||
plugins: ["@typescript-eslint"], | ||
plugins: ['@typescript-eslint'], | ||
rules: { | ||
quotes: ["error", "double"], | ||
"max-len": ["error", 120], | ||
"import/extensions": ["error", "never"], | ||
"max-classes-per-file": ["error", 10], | ||
"import/prefer-default-export": "off", | ||
"object-curly-newline": "off", | ||
quotes: ['error', 'single'], | ||
'max-len': ['error', 120], | ||
'import/extensions': ['error', 'never'], | ||
'max-classes-per-file': ['error', 10], | ||
'import/prefer-default-export': 'off', | ||
'object-curly-newline': 'off', | ||
'no-use-before-define': 'off', | ||
'@typescript-eslint/no-use-before-define': ['error', { functions: false, classes: false }], | ||
}, | ||
settings: { | ||
"import/resolver": { | ||
'import/resolver': { | ||
node: { | ||
extensions: [".js", ".jsx", ".ts", ".tsx"], | ||
extensions: ['.js', '.jsx', '.ts', '.tsx'], | ||
}, | ||
@@ -28,0 +33,0 @@ }, |
@@ -24,3 +24,8 @@ "use strict"; | ||
*/ | ||
this.getAccount = (address, params = {}) => this.http.request(Object.assign({ path: `/accounts/${address}`, method: "GET", format: "json" }, params)); | ||
this.getAccount = (address, params = {}) => this.http.request({ | ||
path: `/accounts/${address}`, | ||
method: "GET", | ||
format: "json", | ||
...params, | ||
}); | ||
/** | ||
@@ -34,3 +39,9 @@ * No description | ||
*/ | ||
this.getAccountResources = (address, query, params = {}) => this.http.request(Object.assign({ path: `/accounts/${address}/resources`, method: "GET", query: query, format: "json" }, params)); | ||
this.getAccountResources = (address, query, params = {}) => this.http.request({ | ||
path: `/accounts/${address}/resources`, | ||
method: "GET", | ||
query: query, | ||
format: "json", | ||
...params, | ||
}); | ||
/** | ||
@@ -44,3 +55,9 @@ * @description This API renders a resource identified by the owner account `address` and the `resource_type`, at a ledger version (AKA transaction version) specified as a query param, otherwise the latest version is used. | ||
*/ | ||
this.getAccountResource = (address, resourceType, query, params = {}) => this.http.request(Object.assign({ path: `/accounts/${address}/resource/${resourceType}`, method: "GET", query: query, format: "json" }, params)); | ||
this.getAccountResource = (address, resourceType, query, params = {}) => this.http.request({ | ||
path: `/accounts/${address}/resource/${resourceType}`, | ||
method: "GET", | ||
query: query, | ||
format: "json", | ||
...params, | ||
}); | ||
/** | ||
@@ -54,3 +71,9 @@ * No description | ||
*/ | ||
this.getAccountModules = (address, query, params = {}) => this.http.request(Object.assign({ path: `/accounts/${address}/modules`, method: "GET", query: query, format: "json" }, params)); | ||
this.getAccountModules = (address, query, params = {}) => this.http.request({ | ||
path: `/accounts/${address}/modules`, | ||
method: "GET", | ||
query: query, | ||
format: "json", | ||
...params, | ||
}); | ||
/** | ||
@@ -64,3 +87,9 @@ * @description This API renders a Move module identified by the module id. A module id consists of the module owner `address` and the `module_name`. The module is rendered at a ledger version (AKA transaction version) specified as a query param, otherwise the latest version is used. | ||
*/ | ||
this.getAccountModule = (address, moduleName, query, params = {}) => this.http.request(Object.assign({ path: `/accounts/${address}/module/${moduleName}`, method: "GET", query: query, format: "json" }, params)); | ||
this.getAccountModule = (address, moduleName, query, params = {}) => this.http.request({ | ||
path: `/accounts/${address}/module/${moduleName}`, | ||
method: "GET", | ||
query: query, | ||
format: "json", | ||
...params, | ||
}); | ||
/** | ||
@@ -74,3 +103,9 @@ * No description | ||
*/ | ||
this.getAccountTransactions = (address, query, params = {}) => this.http.request(Object.assign({ path: `/accounts/${address}/transactions`, method: "GET", query: query, format: "json" }, params)); | ||
this.getAccountTransactions = (address, query, params = {}) => this.http.request({ | ||
path: `/accounts/${address}/transactions`, | ||
method: "GET", | ||
query: query, | ||
format: "json", | ||
...params, | ||
}); | ||
/** | ||
@@ -84,3 +119,9 @@ * @description This API extracts event key from the account resource identified by the `event_handle_struct` and `field_name`, then returns events identified by the event key. | ||
*/ | ||
this.getEventsByEventHandle = (address, eventHandleStruct, fieldName, query, params = {}) => this.http.request(Object.assign({ path: `/accounts/${address}/events/${eventHandleStruct}/${fieldName}`, method: "GET", query: query, format: "json" }, params)); | ||
this.getEventsByEventHandle = (address, eventHandleStruct, fieldName, query, params = {}) => this.http.request({ | ||
path: `/accounts/${address}/events/${eventHandleStruct}/${fieldName}`, | ||
method: "GET", | ||
query: query, | ||
format: "json", | ||
...params, | ||
}); | ||
this.http = http; | ||
@@ -87,0 +128,0 @@ } |
@@ -412,3 +412,3 @@ export interface AptosError { | ||
/** @example XDX */ | ||
gas_currency_code: string; | ||
gas_currency_code?: string; | ||
/** | ||
@@ -421,2 +421,5 @@ * Timestamp in seconds, e.g. transaction expiration timestamp. | ||
} | ||
export declare type UserCreateSigningMessageRequest = UserTransactionRequest & { | ||
secondary_signers?: Address[]; | ||
}; | ||
/** | ||
@@ -428,3 +431,3 @@ * This schema is used for appending `signature` field to another schema. | ||
} | ||
export declare type Transaction = PendingTransaction | GenesisTransaction | UserTransaction | BlockMetadataTransaction; | ||
export declare type Transaction = PendingTransaction | GenesisTransaction | UserTransaction | BlockMetadataTransaction | StateCheckpointTransaction; | ||
export declare type SubmitTransactionRequest = UserTransactionRequest & UserTransactionSignature; | ||
@@ -435,3 +438,3 @@ export declare type PendingTransaction = { | ||
} & UserTransactionRequest & UserTransactionSignature; | ||
export declare type OnChainTransaction = GenesisTransaction | UserTransaction | BlockMetadataTransaction; | ||
export declare type OnChainTransaction = GenesisTransaction | UserTransaction | BlockMetadataTransaction | StateCheckpointTransaction; | ||
export interface OnChainTransactionInfo { | ||
@@ -501,2 +504,6 @@ /** Unsigned int64 type value */ | ||
} & OnChainTransactionInfo; | ||
export declare type StateCheckpointTransaction = { | ||
type: string; | ||
timestamp: TimestampUsec; | ||
} & OnChainTransactionInfo; | ||
export declare type TransactionPayload = ScriptFunctionPayload | ScriptPayload | ModuleBundlePayload | WriteSetPayload; | ||
@@ -708,8 +715,23 @@ /** | ||
state_key_hash: HexEncodedBytes; | ||
/** Table item write */ | ||
data: { | ||
handle: HexEncodedBytes; | ||
key: HexEncodedBytes; | ||
value: HexEncodedBytes; | ||
}; | ||
/** | ||
* All bytes data are represented as hex-encoded string prefixed with `0x` and fulfilled with | ||
* two hex digits per byte. | ||
* | ||
* Different with `Address` type, hex-encoded bytes should not trim any zeros. | ||
*/ | ||
handle: HexEncodedBytes; | ||
/** | ||
* All bytes data are represented as hex-encoded string prefixed with `0x` and fulfilled with | ||
* two hex digits per byte. | ||
* | ||
* Different with `Address` type, hex-encoded bytes should not trim any zeros. | ||
*/ | ||
key: HexEncodedBytes; | ||
/** | ||
* All bytes data are represented as hex-encoded string prefixed with `0x` and fulfilled with | ||
* two hex digits per byte. | ||
* | ||
* Different with `Address` type, hex-encoded bytes should not trim any zeros. | ||
*/ | ||
value: HexEncodedBytes; | ||
} | ||
@@ -716,0 +738,0 @@ export interface Script { |
@@ -24,3 +24,8 @@ "use strict"; | ||
*/ | ||
this.getEventsByEventKey = (eventKey, params = {}) => this.http.request(Object.assign({ path: `/events/${eventKey}`, method: "GET", format: "json" }, params)); | ||
this.getEventsByEventKey = (eventKey, params = {}) => this.http.request({ | ||
path: `/events/${eventKey}`, | ||
method: "GET", | ||
format: "json", | ||
...params, | ||
}); | ||
this.http = http; | ||
@@ -27,0 +32,0 @@ } |
@@ -12,22 +12,2 @@ "use strict"; | ||
*/ | ||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||
return new (P || (P = Promise))(function (resolve, reject) { | ||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } | ||
step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||
}); | ||
}; | ||
var __rest = (this && this.__rest) || function (s, e) { | ||
var t = {}; | ||
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) | ||
t[p] = s[p]; | ||
if (s != null && typeof Object.getOwnPropertySymbols === "function") | ||
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { | ||
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) | ||
t[p[i]] = s[p[i]]; | ||
} | ||
return t; | ||
}; | ||
var __importDefault = (this && this.__importDefault) || function (mod) { | ||
@@ -46,4 +26,3 @@ return (mod && mod.__esModule) ? mod : { "default": mod }; | ||
class HttpClient { | ||
constructor(_a = {}) { | ||
var { securityWorker, secure, format } = _a, axiosConfig = __rest(_a, ["securityWorker", "secure", "format"]); | ||
constructor({ securityWorker, secure, format, ...axiosConfig } = {}) { | ||
this.securityData = null; | ||
@@ -53,11 +32,9 @@ this.setSecurityData = (data) => { | ||
}; | ||
this.request = (_b) => __awaiter(this, void 0, void 0, function* () { | ||
var { secure, path, type, query, format, body } = _b, params = __rest(_b, ["secure", "path", "type", "query", "format", "body"]); | ||
this.request = async ({ secure, path, type, query, format, body, ...params }) => { | ||
const secureParams = ((typeof secure === "boolean" ? secure : this.secure) && | ||
this.securityWorker && | ||
(yield this.securityWorker(this.securityData))) || | ||
(await this.securityWorker(this.securityData))) || | ||
{}; | ||
const requestParams = this.mergeRequestParams(params, secureParams); | ||
const responseFormat = (format && this.format) || void 0; | ||
// @ts-ignore | ||
if (type === ContentType.FormData && body && body !== null && typeof body === "object") { | ||
@@ -72,5 +49,15 @@ // @ts-ignore | ||
} | ||
return this.instance.request(Object.assign(Object.assign({}, requestParams), { headers: Object.assign(Object.assign({}, (type && type !== ContentType.FormData ? { "Content-Type": type } : {})), (requestParams.headers || {})), params: query, responseType: responseFormat, data: body, url: path })); | ||
}); | ||
this.instance = axios_1.default.create(Object.assign(Object.assign({}, axiosConfig), { baseURL: axiosConfig.baseURL || "" })); | ||
return this.instance.request({ | ||
...requestParams, | ||
headers: { | ||
...(type && type !== ContentType.FormData ? { "Content-Type": type } : {}), | ||
...(requestParams.headers || {}), | ||
}, | ||
params: query, | ||
responseType: responseFormat, | ||
data: body, | ||
url: path, | ||
}); | ||
}; | ||
this.instance = axios_1.default.create({ ...axiosConfig, baseURL: axiosConfig.baseURL || "" }); | ||
this.secure = secure; | ||
@@ -81,5 +68,13 @@ this.format = format; | ||
mergeRequestParams(params1, params2) { | ||
return Object.assign(Object.assign(Object.assign(Object.assign({}, this.instance.defaults), params1), (params2 || {})), { | ||
return { | ||
...this.instance.defaults, | ||
...params1, | ||
...(params2 || {}), | ||
// @ts-ignore | ||
headers: Object.assign(Object.assign(Object.assign({}, (this.instance.defaults.headers || {})), (params1.headers || {})), ((params2 && params2.headers) || {})) }); | ||
headers: { | ||
...(this.instance.defaults.headers || {}), | ||
...(params1.headers || {}), | ||
...((params2 && params2.headers) || {}), | ||
}, | ||
}; | ||
} | ||
@@ -86,0 +81,0 @@ createFormData(input) { |
@@ -24,3 +24,7 @@ "use strict"; | ||
*/ | ||
this.getSpecYaml = (params = {}) => this.http.request(Object.assign({ path: `/openapi.yaml`, method: "GET" }, params)); | ||
this.getSpecYaml = (params = {}) => this.http.request({ | ||
path: `/openapi.yaml`, | ||
method: "GET", | ||
...params, | ||
}); | ||
this.http = http; | ||
@@ -27,0 +31,0 @@ } |
@@ -24,3 +24,7 @@ "use strict"; | ||
*/ | ||
this.getSpecHtml = (params = {}) => this.http.request(Object.assign({ path: `/spec.html`, method: "GET" }, params)); | ||
this.getSpecHtml = (params = {}) => this.http.request({ | ||
path: `/spec.html`, | ||
method: "GET", | ||
...params, | ||
}); | ||
this.http = http; | ||
@@ -27,0 +31,0 @@ } |
@@ -25,3 +25,10 @@ "use strict"; | ||
*/ | ||
this.getTableItem = (tableHandle, data, params = {}) => this.http.request(Object.assign({ path: `/tables/${tableHandle}/item`, method: "POST", body: data, type: http_client_1.ContentType.Json, format: "json" }, params)); | ||
this.getTableItem = (tableHandle, data, params = {}) => this.http.request({ | ||
path: `/tables/${tableHandle}/item`, | ||
method: "POST", | ||
body: data, | ||
type: http_client_1.ContentType.Json, | ||
format: "json", | ||
...params, | ||
}); | ||
this.http = http; | ||
@@ -28,0 +35,0 @@ } |
@@ -1,2 +0,2 @@ | ||
import { HexEncodedBytes, OnChainTransaction, PendingTransaction, SubmitTransactionRequest, Transaction, UserTransactionRequest } from "./data-contracts"; | ||
import { HexEncodedBytes, OnChainTransaction, PendingTransaction, SubmitTransactionRequest, Transaction, UserCreateSigningMessageRequest } from "./data-contracts"; | ||
import { HttpClient, RequestParams } from "./http-client"; | ||
@@ -44,3 +44,3 @@ export declare class Transactions<SecurityDataType = unknown> { | ||
*/ | ||
createSigningMessage: (data: UserTransactionRequest, params?: RequestParams) => Promise<import("axios").AxiosResponse<{ | ||
createSigningMessage: (data: UserCreateSigningMessageRequest, params?: RequestParams) => Promise<import("axios").AxiosResponse<{ | ||
message: HexEncodedBytes; | ||
@@ -47,0 +47,0 @@ }, any>>; |
@@ -25,3 +25,9 @@ "use strict"; | ||
*/ | ||
this.getTransactions = (query, params = {}) => this.http.request(Object.assign({ path: `/transactions`, method: "GET", query: query, format: "json" }, params)); | ||
this.getTransactions = (query, params = {}) => this.http.request({ | ||
path: `/transactions`, | ||
method: "GET", | ||
query: query, | ||
format: "json", | ||
...params, | ||
}); | ||
/** | ||
@@ -35,3 +41,10 @@ * @description **Submit transaction using JSON without additional tools** * Send [POST /transactions/signing_message](#operation/create-signing-message) to create transaction signing message. * Sign the transaction signing message and create transaction signature. * Submit the user transaction request with the transaction siganture. The request header "Content-Type" must set to "application/json". | ||
*/ | ||
this.submitTransaction = (data, params = {}) => this.http.request(Object.assign({ path: `/transactions`, method: "POST", body: data, type: http_client_1.ContentType.Json, format: "json" }, params)); | ||
this.submitTransaction = (data, params = {}) => this.http.request({ | ||
path: `/transactions`, | ||
method: "POST", | ||
body: data, | ||
type: http_client_1.ContentType.Json, | ||
format: "json", | ||
...params, | ||
}); | ||
/** | ||
@@ -45,3 +58,8 @@ * @description There are two types of transaction identifiers: 1. Transaction hash: included in any transaction JSON respond from server. 2. Transaction version: included in on-chain transaction JSON respond from server. 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. To create a transaction hash: 1. Create hash message bytes: "Aptos::Transaction" bytes + BCS bytes of [Transaction](https://aptos-labs.github.io/aptos-core/aptos_types/transaction/enum.Transaction.html). 2. Apply hash algorithm `SHA3-256` to the hash message bytes. 3. Hex-encode the hash bytes with `0x` prefix. | ||
*/ | ||
this.getTransaction = (txnHashOrVersion, params = {}) => this.http.request(Object.assign({ path: `/transactions/${txnHashOrVersion}`, method: "GET", format: "json" }, params)); | ||
this.getTransaction = (txnHashOrVersion, params = {}) => this.http.request({ | ||
path: `/transactions/${txnHashOrVersion}`, | ||
method: "GET", | ||
format: "json", | ||
...params, | ||
}); | ||
/** | ||
@@ -55,3 +73,10 @@ * @description This API creates transaction signing message for client to create transaction signature. The success response contains hex-encoded signing message bytes. **To sign the message** 1. Client first needs to HEX decode the `message` into bytes. 2. Then sign the bytes to create signature. | ||
*/ | ||
this.createSigningMessage = (data, params = {}) => this.http.request(Object.assign({ path: `/transactions/signing_message`, method: "POST", body: data, type: http_client_1.ContentType.Json, format: "json" }, params)); | ||
this.createSigningMessage = (data, params = {}) => this.http.request({ | ||
path: `/transactions/signing_message`, | ||
method: "POST", | ||
body: data, | ||
type: http_client_1.ContentType.Json, | ||
format: "json", | ||
...params, | ||
}); | ||
this.http = http; | ||
@@ -58,0 +83,0 @@ } |
@@ -1,5 +0,5 @@ | ||
import * as Nacl from "tweetnacl"; | ||
import { Buffer } from "buffer/"; | ||
import { HexString, MaybeHexString } from "./hex_string"; | ||
import { Types } from "./types"; | ||
import * as Nacl from 'tweetnacl'; | ||
import { Buffer } from 'buffer/'; | ||
import { HexString, MaybeHexString } from './hex_string'; | ||
import { Types } from './types'; | ||
export interface AptosAccountObject { | ||
@@ -6,0 +6,0 @@ address?: string; |
@@ -55,3 +55,3 @@ "use strict"; | ||
hash.update(buffer_1.Buffer.from(this.signingKey.publicKey)); | ||
hash.update("\x00"); | ||
hash.update('\x00'); | ||
this.authKeyCached = new hex_string_1.HexString(hash.hex()); | ||
@@ -63,7 +63,7 @@ } | ||
pubKey() { | ||
return hex_string_1.HexString.ensure(buffer_1.Buffer.from(this.signingKey.publicKey).toString("hex")); | ||
return hex_string_1.HexString.ensure(buffer_1.Buffer.from(this.signingKey.publicKey).toString('hex')); | ||
} | ||
signBuffer(buffer) { | ||
const signature = Nacl.sign(buffer, this.signingKey.secretKey); | ||
return hex_string_1.HexString.ensure(buffer_1.Buffer.from(signature).toString("hex").slice(0, 128)); | ||
return hex_string_1.HexString.ensure(buffer_1.Buffer.from(signature).toString('hex').slice(0, 128)); | ||
} | ||
@@ -70,0 +70,0 @@ signHexString(hexString) { |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
const aptos_account_1 = require("./aptos_account"); | ||
const AptosAccountObject = { | ||
address: "0x978c213990c4833df71548df7ce49d54c759d6b6d932de22b24d56060b7af2aa", | ||
privateKeyHex: "0xc5338cd251c22daa8c9c9cc94f498cc8a5c7e1d2e75287a5dda91096fe64efa5de19e5d1880cac87d57484ce9ed2e84cf0f9599f12e7cc3a52e4e7657a763f2c", | ||
publicKeyHex: "0xde19e5d1880cac87d57484ce9ed2e84cf0f9599f12e7cc3a52e4e7657a763f2c", | ||
const aptosAccountObject = { | ||
address: '0x978c213990c4833df71548df7ce49d54c759d6b6d932de22b24d56060b7af2aa', | ||
privateKeyHex: | ||
// eslint-disable-next-line max-len | ||
'0xc5338cd251c22daa8c9c9cc94f498cc8a5c7e1d2e75287a5dda91096fe64efa5de19e5d1880cac87d57484ce9ed2e84cf0f9599f12e7cc3a52e4e7657a763f2c', | ||
publicKeyHex: '0xde19e5d1880cac87d57484ce9ed2e84cf0f9599f12e7cc3a52e4e7657a763f2c', | ||
}; | ||
test("generates random accounts", () => { | ||
test('generates random accounts', () => { | ||
const a1 = new aptos_account_1.AptosAccount(); | ||
@@ -15,19 +17,19 @@ const a2 = new aptos_account_1.AptosAccount(); | ||
}); | ||
test("accepts custom address", () => { | ||
const address = "0x777"; | ||
test('accepts custom address', () => { | ||
const address = '0x777'; | ||
const a1 = new aptos_account_1.AptosAccount(null, address); | ||
expect(a1.address().hex()).toBe(address); | ||
}); | ||
test("Deserializes from AptosAccountObject", () => { | ||
const a1 = aptos_account_1.AptosAccount.fromAptosAccountObject(AptosAccountObject); | ||
expect(a1.address().hex()).toBe(AptosAccountObject.address); | ||
expect(a1.pubKey().hex()).toBe(AptosAccountObject.publicKeyHex); | ||
test('Deserializes from AptosAccountObject', () => { | ||
const a1 = aptos_account_1.AptosAccount.fromAptosAccountObject(aptosAccountObject); | ||
expect(a1.address().hex()).toBe(aptosAccountObject.address); | ||
expect(a1.pubKey().hex()).toBe(aptosAccountObject.publicKeyHex); | ||
}); | ||
test("Deserializes from AptosAccountObject without address", () => { | ||
const privateKeyObject = { privateKeyHex: AptosAccountObject.privateKeyHex }; | ||
test('Deserializes from AptosAccountObject without address', () => { | ||
const privateKeyObject = { privateKeyHex: aptosAccountObject.privateKeyHex }; | ||
const a1 = aptos_account_1.AptosAccount.fromAptosAccountObject(privateKeyObject); | ||
expect(a1.address().hex()).toBe(AptosAccountObject.address); | ||
expect(a1.pubKey().hex()).toBe(AptosAccountObject.publicKeyHex); | ||
expect(a1.address().hex()).toBe(aptosAccountObject.address); | ||
expect(a1.pubKey().hex()).toBe(aptosAccountObject.publicKeyHex); | ||
}); | ||
test("Serializes/Deserializes", () => { | ||
test('Serializes/Deserializes', () => { | ||
const a1 = new aptos_account_1.AptosAccount(); | ||
@@ -38,6 +40,8 @@ const a2 = aptos_account_1.AptosAccount.fromAptosAccountObject(a1.toPrivateKeyObject()); | ||
}); | ||
test("Signs Strings", () => { | ||
const a1 = aptos_account_1.AptosAccount.fromAptosAccountObject(AptosAccountObject); | ||
expect(a1.signHexString("0x77777").hex()).toBe("0xc5de9e40ac00b371cd83b1c197fa5b665b7449b33cd3cdd305bb78222e06a671a49625ab9aea8a039d4bb70e275768084d62b094bc1b31964f2357b7c1af7e0d"); | ||
test('Signs Strings', () => { | ||
const a1 = aptos_account_1.AptosAccount.fromAptosAccountObject(aptosAccountObject); | ||
expect(a1.signHexString('0x77777').hex()).toBe( | ||
// eslint-disable-next-line max-len | ||
'0xc5de9e40ac00b371cd83b1c197fa5b665b7449b33cd3cdd305bb78222e06a671a49625ab9aea8a039d4bb70e275768084d62b094bc1b31964f2357b7c1af7e0d'); | ||
}); | ||
//# sourceMappingURL=aptos_account.test.js.map |
@@ -1,10 +0,11 @@ | ||
import { AxiosRequestConfig, AxiosResponse } from "axios"; | ||
import { Accounts } from "./api/Accounts"; | ||
import { Events } from "./api/Events"; | ||
import { Transactions } from "./api/Transactions"; | ||
import { HttpClient, RequestParams } from "./api/http-client"; | ||
import { MaybeHexString } from "./hex_string"; | ||
import { AptosAccount } from "./aptos_account"; | ||
import { Types } from "./types"; | ||
import { Tables } from "./api/Tables"; | ||
import { AxiosRequestConfig, AxiosResponse } from 'axios'; | ||
import { Accounts } from './api/Accounts'; | ||
import { Events } from './api/Events'; | ||
import { Transactions } from './api/Transactions'; | ||
import { HttpClient, RequestParams } from './api/http-client'; | ||
import { MaybeHexString } from './hex_string'; | ||
import { AptosAccount } from './aptos_account'; | ||
import { Types } from './types'; | ||
import { Tables } from './api/Tables'; | ||
import * as TxnBuilderTypes from './transaction_builder/aptos_types'; | ||
export declare class RequestError extends Error { | ||
@@ -15,3 +16,3 @@ response?: AxiosResponse<any, Types.AptosError>; | ||
} | ||
export declare type AptosClientConfig = Omit<AxiosRequestConfig, "data" | "cancelToken" | "method">; | ||
export declare type AptosClientConfig = Omit<AxiosRequestConfig, 'data' | 'cancelToken' | 'method'>; | ||
export declare function raiseForStatus<T>(expectedStatus: number, response: AxiosResponse<T, Types.AptosError>, requestContent?: any): void; | ||
@@ -49,2 +50,4 @@ export declare class AptosClient { | ||
}): Promise<Types.AccountResource>; | ||
/** Generates a signed transaction that can be submitted to the chain for execution. */ | ||
static generateBCSTransaction(accountFrom: AptosAccount, rawTxn: TxnBuilderTypes.RawTransaction): Promise<Uint8Array>; | ||
/** Generates a transaction request that can be submitted to produce a raw transaction that | ||
@@ -65,4 +68,6 @@ * can be signed, which upon being signed can be submitted to the blockchain. */ | ||
}): Promise<Types.Event[]>; | ||
/** Submits a signed transaction to the blockchain. */ | ||
/** Submits a signed transaction to the transaction endpoint that takes JSON payload. */ | ||
submitTransaction(signedTxnRequest: Types.SubmitTransactionRequest): Promise<Types.PendingTransaction>; | ||
/** Submits a signed transaction to the the endpoint that takes BCS payload. */ | ||
submitSignedBCSTransaction(signedTxn: Uint8Array): Promise<Types.PendingTransaction>; | ||
getTransactions(query?: { | ||
@@ -77,4 +82,5 @@ start?: number; | ||
getLedgerInfo(params?: RequestParams): Promise<Types.LedgerInfo>; | ||
getChainId(params?: RequestParams): Promise<number>; | ||
getTableItem(handle: string, data: Types.TableItemRequest, params?: RequestParams): Promise<any>; | ||
} | ||
//# sourceMappingURL=aptos_client.d.ts.map |
"use strict"; | ||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||
return new (P || (P = Promise))(function (resolve, reject) { | ||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } | ||
step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||
}); | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
@@ -20,8 +11,8 @@ exports.AptosClient = exports.raiseForStatus = exports.RequestError = void 0; | ||
const Tables_1 = require("./api/Tables"); | ||
const transaction_builder_1 = require("./transaction_builder"); | ||
class RequestError extends Error { | ||
constructor(message, response, requestBody) { | ||
var _a, _b; | ||
const data = JSON.stringify(response.data); | ||
const hostAndPath = [(_a = response.request) === null || _a === void 0 ? void 0 : _a.host, (_b = response.request) === null || _b === void 0 ? void 0 : _b.path].filter((e) => !!e).join(""); | ||
super(`${message} - ${data}${hostAndPath ? ` @ ${hostAndPath}` : ""}${requestBody ? ` : ${requestBody}` : ""}`); | ||
const hostAndPath = [response.request?.host, response.request?.path].filter((e) => !!e).join(''); | ||
super(`${message} - ${data}${hostAndPath ? ` @ ${hostAndPath}` : ''}${requestBody ? ` : ${requestBody}` : ''}`); | ||
this.response = response; | ||
@@ -46,3 +37,8 @@ this.requestBody = requestBody; | ||
// `withCredentials` ensures cookie handling | ||
this.client = new http_client_1.HttpClient(Object.assign({ withCredentials: false, baseURL: nodeUrl, validateStatus: () => true }, (config || {}))); | ||
this.client = new http_client_1.HttpClient({ | ||
withCredentials: false, | ||
baseURL: nodeUrl, | ||
validateStatus: () => true, | ||
...(config || {}), | ||
}); | ||
// Initialize routes | ||
@@ -55,59 +51,63 @@ this.accounts = new Accounts_1.Accounts(this.client); | ||
/** Returns the sequence number and authentication key for an account */ | ||
getAccount(accountAddress) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const response = yield this.accounts.getAccount(hex_string_1.HexString.ensure(accountAddress).hex()); | ||
raiseForStatus(200, response); | ||
return response.data; | ||
}); | ||
async getAccount(accountAddress) { | ||
const response = await this.accounts.getAccount(hex_string_1.HexString.ensure(accountAddress).hex()); | ||
raiseForStatus(200, response); | ||
return response.data; | ||
} | ||
/** Returns transactions sent by the account */ | ||
getAccountTransactions(accountAddress, query) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const response = yield this.accounts.getAccountTransactions(hex_string_1.HexString.ensure(accountAddress).hex(), query); | ||
raiseForStatus(200, response); | ||
return response.data; | ||
}); | ||
async getAccountTransactions(accountAddress, query) { | ||
const response = await this.accounts.getAccountTransactions(hex_string_1.HexString.ensure(accountAddress).hex(), query); | ||
raiseForStatus(200, response); | ||
return response.data; | ||
} | ||
/** Returns all modules associated with the account */ | ||
getAccountModules(accountAddress, query) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const response = yield this.accounts.getAccountModules(hex_string_1.HexString.ensure(accountAddress).hex(), query); | ||
raiseForStatus(200, response); | ||
return response.data; | ||
}); | ||
async getAccountModules(accountAddress, query) { | ||
const response = await this.accounts.getAccountModules(hex_string_1.HexString.ensure(accountAddress).hex(), query); | ||
raiseForStatus(200, response); | ||
return response.data; | ||
} | ||
/** Returns the module identified by address and module name */ | ||
getAccountModule(accountAddress, moduleName, query) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const response = yield this.accounts.getAccountModule(hex_string_1.HexString.ensure(accountAddress).hex(), moduleName, query); | ||
raiseForStatus(200, response); | ||
return response.data; | ||
}); | ||
async getAccountModule(accountAddress, moduleName, query) { | ||
const response = await this.accounts.getAccountModule(hex_string_1.HexString.ensure(accountAddress).hex(), moduleName, query); | ||
raiseForStatus(200, response); | ||
return response.data; | ||
} | ||
/** Returns all resources associated with the account */ | ||
getAccountResources(accountAddress, query) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const response = yield this.accounts.getAccountResources(hex_string_1.HexString.ensure(accountAddress).hex(), query); | ||
raiseForStatus(200, response); | ||
return response.data; | ||
}); | ||
async getAccountResources(accountAddress, query) { | ||
const response = await this.accounts.getAccountResources(hex_string_1.HexString.ensure(accountAddress).hex(), query); | ||
raiseForStatus(200, response); | ||
return response.data; | ||
} | ||
/** Returns the resource by the address and resource type */ | ||
getAccountResource(accountAddress, resourceType, query) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const response = yield this.accounts.getAccountResource(hex_string_1.HexString.ensure(accountAddress).hex(), resourceType, query); | ||
raiseForStatus(200, response); | ||
return response.data; | ||
}); | ||
async getAccountResource(accountAddress, resourceType, query) { | ||
const response = await this.accounts.getAccountResource(hex_string_1.HexString.ensure(accountAddress).hex(), resourceType, query); | ||
raiseForStatus(200, response); | ||
return response.data; | ||
} | ||
/** Generates a signed transaction that can be submitted to the chain for execution. */ | ||
static async generateBCSTransaction(accountFrom, rawTxn) { | ||
const txnBuilder = new transaction_builder_1.TransactionBuilderEd25519((signingMessage) => { | ||
// @ts-ignore | ||
const sigHexStr = accountFrom.signBuffer(signingMessage); | ||
return sigHexStr.toUint8Array(); | ||
}, accountFrom.pubKey().toUint8Array()); | ||
const signedTxn = await txnBuilder.sign(rawTxn); | ||
return signedTxn; | ||
} | ||
/** 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. */ | ||
generateTransaction(sender, payload, options) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const senderAddress = hex_string_1.HexString.ensure(sender); | ||
const account = yield this.getAccount(senderAddress); | ||
return Object.assign({ 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(), payload }, (options || {})); | ||
}); | ||
async generateTransaction(sender, payload, options) { | ||
const senderAddress = hex_string_1.HexString.ensure(sender); | ||
const account = await this.getAccount(senderAddress); | ||
return { | ||
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(), | ||
payload, | ||
...(options || {}), | ||
}; | ||
} | ||
@@ -117,99 +117,101 @@ /** Converts a transaction request by `generate_transaction` into it's binary hex BCS representation, ready for | ||
* Generally you may want to use `signTransaction`, as it takes care of this step + signing */ | ||
createSigningMessage(txnRequest) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const response = yield this.transactions.createSigningMessage(txnRequest); | ||
raiseForStatus(200, response, txnRequest); | ||
const { message } = response.data; | ||
return message; | ||
}); | ||
async createSigningMessage(txnRequest) { | ||
const response = await this.transactions.createSigningMessage(txnRequest); | ||
raiseForStatus(200, response, txnRequest); | ||
const { message } = response.data; | ||
return message; | ||
} | ||
/** Converts a transaction request produced by `generate_transaction` into a properly signed | ||
* transaction, which can then be submitted to the blockchain. */ | ||
signTransaction(accountFrom, txnRequest) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const message = yield this.createSigningMessage(txnRequest); | ||
const signatureHex = accountFrom.signHexString(message.substring(2)); | ||
const transactionSignature = { | ||
type: "ed25519_signature", | ||
public_key: accountFrom.pubKey().hex(), | ||
signature: signatureHex.hex(), | ||
}; | ||
return Object.assign({ signature: transactionSignature }, txnRequest); | ||
}); | ||
async signTransaction(accountFrom, txnRequest) { | ||
const message = await this.createSigningMessage(txnRequest); | ||
const signatureHex = accountFrom.signHexString(message.substring(2)); | ||
const transactionSignature = { | ||
type: 'ed25519_signature', | ||
public_key: accountFrom.pubKey().hex(), | ||
signature: signatureHex.hex(), | ||
}; | ||
return { signature: transactionSignature, ...txnRequest }; | ||
} | ||
getEventsByEventKey(eventKey) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const response = yield this.events.getEventsByEventKey(eventKey); | ||
raiseForStatus(200, response, `eventKey: ${eventKey}`); | ||
return response.data; | ||
}); | ||
async getEventsByEventKey(eventKey) { | ||
const response = await this.events.getEventsByEventKey(eventKey); | ||
raiseForStatus(200, response, `eventKey: ${eventKey}`); | ||
return response.data; | ||
} | ||
getEventsByEventHandle(address, eventHandleStruct, fieldName, query) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const response = yield this.accounts.getEventsByEventHandle(hex_string_1.HexString.ensure(address).hex(), eventHandleStruct, fieldName, query); | ||
raiseForStatus(200, response, { address, eventHandleStruct, fieldName }); | ||
return response.data; | ||
}); | ||
async getEventsByEventHandle(address, eventHandleStruct, fieldName, query) { | ||
const response = await this.accounts.getEventsByEventHandle(hex_string_1.HexString.ensure(address).hex(), eventHandleStruct, fieldName, query); | ||
raiseForStatus(200, response, { address, eventHandleStruct, fieldName }); | ||
return response.data; | ||
} | ||
/** Submits a signed transaction to the blockchain. */ | ||
submitTransaction(signedTxnRequest) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const response = yield this.transactions.submitTransaction(signedTxnRequest); | ||
raiseForStatus(202, response, signedTxnRequest); | ||
return response.data; | ||
}); | ||
/** Submits a signed transaction to the transaction endpoint that takes JSON payload. */ | ||
async submitTransaction(signedTxnRequest) { | ||
const response = await this.transactions.submitTransaction(signedTxnRequest); | ||
raiseForStatus(202, response, signedTxnRequest); | ||
return response.data; | ||
} | ||
getTransactions(query) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const response = yield this.transactions.getTransactions(query); | ||
raiseForStatus(200, response); | ||
return response.data; | ||
/** Submits a signed transaction to the the endpoint that takes BCS payload. */ | ||
async submitSignedBCSTransaction(signedTxn) { | ||
// Need to construct a customized post request for transactions in BCS payload | ||
const httpClient = this.transactions.http; | ||
const response = await httpClient.request({ | ||
path: '/transactions', | ||
method: 'POST', | ||
body: signedTxn, | ||
// @ts-ignore | ||
type: 'application/x.aptos.signed_transaction+bcs', | ||
format: 'json', | ||
}); | ||
raiseForStatus(202, response, signedTxn); | ||
return response.data; | ||
} | ||
getTransaction(txnHashOrVersion) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const response = yield this.transactions.getTransaction(txnHashOrVersion); | ||
raiseForStatus(200, response, { txnHashOrVersion }); | ||
return response.data; | ||
}); | ||
async getTransactions(query) { | ||
const response = await this.transactions.getTransactions(query); | ||
raiseForStatus(200, response); | ||
return response.data; | ||
} | ||
transactionPending(txnHash) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const response = yield this.transactions.getTransaction(txnHash); | ||
if (response.status === 404) { | ||
return true; | ||
} | ||
raiseForStatus(200, response, txnHash); | ||
return response.data.type === "pending_transaction"; | ||
}); | ||
async getTransaction(txnHashOrVersion) { | ||
const response = await this.transactions.getTransaction(txnHashOrVersion); | ||
raiseForStatus(200, response, { txnHashOrVersion }); | ||
return response.data; | ||
} | ||
async transactionPending(txnHash) { | ||
const response = await this.transactions.getTransaction(txnHash); | ||
if (response.status === 404) { | ||
return true; | ||
} | ||
raiseForStatus(200, response, txnHash); | ||
return response.data.type === 'pending_transaction'; | ||
} | ||
/** Waits up to 10 seconds for a transaction to move past pending state */ | ||
waitForTransaction(txnHash) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
let count = 0; | ||
async waitForTransaction(txnHash) { | ||
let count = 0; | ||
// eslint-disable-next-line no-await-in-loop | ||
while (await this.transactionPending(txnHash)) { | ||
// eslint-disable-next-line no-await-in-loop | ||
while (yield this.transactionPending(txnHash)) { | ||
// eslint-disable-next-line no-await-in-loop | ||
yield (0, util_1.sleep)(1000); | ||
count += 1; | ||
if (count >= 10) { | ||
throw new Error(`Waiting for transaction ${txnHash} timed out!`); | ||
} | ||
await (0, util_1.sleep)(1000); | ||
count += 1; | ||
if (count >= 10) { | ||
throw new Error(`Waiting for transaction ${txnHash} timed out!`); | ||
} | ||
}); | ||
} | ||
} | ||
getLedgerInfo(params = {}) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const result = yield this.client.request(Object.assign({ path: "/", method: "GET", format: "json" }, params)); | ||
return result.data; | ||
async getLedgerInfo(params = {}) { | ||
const result = await this.client.request({ | ||
path: '/', | ||
method: 'GET', | ||
format: 'json', | ||
...params, | ||
}); | ||
return result.data; | ||
} | ||
getTableItem(handle, data, params) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const tableItem = yield this.tables.getTableItem(handle, data, params); | ||
return tableItem; | ||
}); | ||
async getChainId(params = {}) { | ||
const result = await this.getLedgerInfo(params); | ||
return result.chain_id; | ||
} | ||
async getTableItem(handle, data, params) { | ||
const tableItem = await this.tables.getTableItem(handle, data, params); | ||
return tableItem; | ||
} | ||
} | ||
exports.AptosClient = AptosClient; | ||
//# sourceMappingURL=aptos_client.js.map |
"use strict"; | ||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||
return new (P || (P = Promise))(function (resolve, reject) { | ||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } | ||
step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||
}); | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
const aptos_client_1 = require("./aptos_client"); | ||
const util_test_1 = require("./util.test"); | ||
test("gets genesis account", () => __awaiter(void 0, void 0, void 0, function* () { | ||
const faucet_client_1 = require("./faucet_client"); | ||
const aptos_account_1 = require("./aptos_account"); | ||
const aptos_types_1 = require("./transaction_builder/aptos_types"); | ||
const bcs_1 = require("./transaction_builder/bcs"); | ||
test('gets genesis account', async () => { | ||
const client = new aptos_client_1.AptosClient(util_test_1.NODE_URL); | ||
const account = yield client.getAccount("0x1"); | ||
const account = await client.getAccount('0x1'); | ||
expect(account.authentication_key.length).toBe(66); | ||
expect(account.sequence_number).not.toBeNull(); | ||
})); | ||
test("gets transactions", () => __awaiter(void 0, void 0, void 0, function* () { | ||
}); | ||
test('gets transactions', async () => { | ||
const client = new aptos_client_1.AptosClient(util_test_1.NODE_URL); | ||
const transactions = yield client.getTransactions(); | ||
const transactions = await client.getTransactions(); | ||
expect(transactions.length).toBeGreaterThan(0); | ||
})); | ||
test("gets genesis resources", () => __awaiter(void 0, void 0, void 0, function* () { | ||
}); | ||
test('gets genesis resources', async () => { | ||
const client = new aptos_client_1.AptosClient(util_test_1.NODE_URL); | ||
const resources = yield client.getAccountResources("0x1"); | ||
const accountResource = resources.find((r) => r.type === "0x1::Account::Account"); | ||
expect(accountResource.data["self_address"]).toBe("0x1"); | ||
})); | ||
test("gets the Account resource", () => __awaiter(void 0, void 0, void 0, function* () { | ||
const resources = await client.getAccountResources('0x1'); | ||
const accountResource = resources.find((r) => r.type === '0x1::Account::Account'); | ||
expect(accountResource.data.self_address).toBe('0x1'); | ||
}); | ||
test('gets the Account resource', async () => { | ||
const client = new aptos_client_1.AptosClient(util_test_1.NODE_URL); | ||
const accountResource = yield client.getAccountResource("0x1", "0x1::Account::Account"); | ||
expect(accountResource.data["self_address"]).toBe("0x1"); | ||
})); | ||
test("gets ledger info", () => __awaiter(void 0, void 0, void 0, function* () { | ||
const accountResource = await client.getAccountResource('0x1', '0x1::Account::Account'); | ||
expect(accountResource.data.self_address).toBe('0x1'); | ||
}); | ||
test('gets ledger info', async () => { | ||
const client = new aptos_client_1.AptosClient(util_test_1.NODE_URL); | ||
const ledgerInfo = yield client.getLedgerInfo(); | ||
const ledgerInfo = await client.getLedgerInfo(); | ||
expect(ledgerInfo.chain_id).toBeGreaterThan(1); | ||
expect(parseInt(ledgerInfo.ledger_version, 10)).toBeGreaterThan(0); | ||
})); | ||
test("gets account modules", () => __awaiter(void 0, void 0, void 0, function* () { | ||
}); | ||
test('gets account modules', async () => { | ||
const client = new aptos_client_1.AptosClient(util_test_1.NODE_URL); | ||
const modules = yield client.getAccountModules("0x1"); | ||
const module = modules.find((r) => r.abi.name === "TestCoin"); | ||
expect(module.abi.address).toBe("0x1"); | ||
})); | ||
test("gets the TestCoin module", () => __awaiter(void 0, void 0, void 0, function* () { | ||
const modules = await client.getAccountModules('0x1'); | ||
const module = modules.find((r) => r.abi.name === 'TestCoin'); | ||
expect(module.abi.address).toBe('0x1'); | ||
}); | ||
test('gets the TestCoin module', async () => { | ||
const client = new aptos_client_1.AptosClient(util_test_1.NODE_URL); | ||
const module = yield client.getAccountModule("0x1", "TestCoin"); | ||
expect(module.abi.address).toBe("0x1"); | ||
})); | ||
test("test raiseForStatus", () => __awaiter(void 0, void 0, void 0, function* () { | ||
const testData = { hello: "wow" }; | ||
const module = await client.getAccountModule('0x1', 'TestCoin'); | ||
expect(module.abi.address).toBe('0x1'); | ||
}); | ||
test('test raiseForStatus', async () => { | ||
const testData = { hello: 'wow' }; | ||
const fakeResponse = { | ||
status: 200, | ||
statusText: "Status Text", | ||
data: "some string", | ||
statusText: 'Status Text', | ||
data: 'some string', | ||
request: { | ||
host: "host", | ||
path: "/path", | ||
host: 'host', | ||
path: '/path', | ||
}, | ||
@@ -75,3 +70,30 @@ }; | ||
expect(() => (0, aptos_client_1.raiseForStatus)(200, fakeResponse)).toThrow('Status Text - "some string"'); | ||
})); | ||
}); | ||
test('submits bcs 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(); | ||
await faucetClient.fundAccount(account1.address(), 5000); | ||
let resources = await client.getAccountResources(account1.address()); | ||
let accountResource = resources.find((r) => r.type === '0x1::Coin::CoinStore<0x1::TestCoin::TestCoin>'); | ||
expect(accountResource.data.coin.value).toBe('5000'); | ||
const account2 = new aptos_account_1.AptosAccount(); | ||
await faucetClient.fundAccount(account2.address(), 0); | ||
resources = await client.getAccountResources(account2.address()); | ||
accountResource = resources.find((r) => r.type === '0x1::Coin::CoinStore<0x1::TestCoin::TestCoin>'); | ||
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 [{ sequence_number: sequnceNumber }, chainId] = await Promise.all([ | ||
client.getAccount(account1.address()), | ||
client.getChainId(), | ||
]); | ||
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 transactionRes = await client.submitSignedBCSTransaction(bcsTxn); | ||
await client.waitForTransaction(transactionRes.hash); | ||
resources = await client.getAccountResources(account2.address()); | ||
accountResource = resources.find((r) => r.type === '0x1::Coin::CoinStore<0x1::TestCoin::TestCoin>'); | ||
expect(accountResource.data.coin.value).toBe('717'); | ||
}, 30 * 1000); | ||
//# sourceMappingURL=aptos_client.test.js.map |
@@ -1,4 +0,4 @@ | ||
import { AptosClient, AptosClientConfig } from "./aptos_client"; | ||
import { Types } from "./types"; | ||
import { MaybeHexString } from "./hex_string"; | ||
import { AptosClient, AptosClientConfig } from './aptos_client'; | ||
import { Types } from './types'; | ||
import { MaybeHexString } from './hex_string'; | ||
export declare class FaucetClient extends AptosClient { | ||
@@ -5,0 +5,0 @@ faucetUrl: string; |
"use strict"; | ||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||
return new (P || (P = Promise))(function (resolve, reject) { | ||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } | ||
step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||
}); | ||
}; | ||
var __importDefault = (this && this.__importDefault) || function (mod) { | ||
@@ -27,16 +18,14 @@ return (mod && mod.__esModule) ? mod : { "default": mod }; | ||
coins into that account */ | ||
fundAccount(address, amount) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const url = `${this.faucetUrl}/mint?amount=${amount}&address=${hex_string_1.HexString.ensure(address).noPrefix()}`; | ||
const response = yield axios_1.default.post(url, {}, { validateStatus: () => true }); | ||
(0, aptos_client_1.raiseForStatus)(200, response); | ||
const tnxHashes = response.data; | ||
const promises = []; | ||
for (let i = 0; i < tnxHashes.length; i += 1) { | ||
const tnxHash = tnxHashes[i]; | ||
promises.push(this.waitForTransaction(tnxHash)); | ||
} | ||
yield Promise.all(promises); | ||
return tnxHashes; | ||
}); | ||
async fundAccount(address, amount) { | ||
const url = `${this.faucetUrl}/mint?amount=${amount}&address=${hex_string_1.HexString.ensure(address).noPrefix()}`; | ||
const response = await axios_1.default.post(url, {}, { validateStatus: () => true }); | ||
(0, aptos_client_1.raiseForStatus)(200, response); | ||
const tnxHashes = response.data; | ||
const promises = []; | ||
for (let i = 0; i < tnxHashes.length; i += 1) { | ||
const tnxHash = tnxHashes[i]; | ||
promises.push(this.waitForTransaction(tnxHash)); | ||
} | ||
await Promise.all(promises); | ||
return tnxHashes; | ||
} | ||
@@ -43,0 +32,0 @@ } |
"use strict"; | ||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||
return new (P || (P = Promise))(function (resolve, reject) { | ||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } | ||
step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||
}); | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
@@ -17,40 +8,40 @@ const aptos_client_1 = require("./aptos_client"); | ||
const util_test_1 = require("./util.test"); | ||
test("full tutorial faucet flow", () => __awaiter(void 0, void 0, void 0, function* () { | ||
test('full tutorial faucet flow', 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); | ||
const account1 = new aptos_account_1.AptosAccount(); | ||
const txns = yield faucetClient.fundAccount(account1.address(), 5000); | ||
const tx1 = yield client.getTransaction(txns[1]); | ||
expect(tx1.type).toBe("user_transaction"); | ||
let resources = yield client.getAccountResources(account1.address()); | ||
let accountResource = resources.find((r) => r.type === "0x1::TestCoin::Balance"); | ||
expect(accountResource.data.coin.value).toBe("5000"); | ||
const txns = await faucetClient.fundAccount(account1.address(), 5000); | ||
const tx1 = await client.getTransaction(txns[1]); | ||
expect(tx1.type).toBe('user_transaction'); | ||
let resources = await client.getAccountResources(account1.address()); | ||
let accountResource = resources.find((r) => r.type === '0x1::Coin::CoinStore<0x1::TestCoin::TestCoin>'); | ||
expect(accountResource.data.coin.value).toBe('5000'); | ||
const account2 = new aptos_account_1.AptosAccount(); | ||
yield faucetClient.fundAccount(account2.address(), 0); | ||
resources = yield client.getAccountResources(account2.address()); | ||
accountResource = resources.find((r) => r.type === "0x1::TestCoin::Balance"); | ||
expect(accountResource.data.coin.value).toBe("0"); | ||
await faucetClient.fundAccount(account2.address(), 0); | ||
resources = await client.getAccountResources(account2.address()); | ||
accountResource = resources.find((r) => r.type === '0x1::Coin::CoinStore<0x1::TestCoin::TestCoin>'); | ||
expect(accountResource.data.coin.value).toBe('0'); | ||
const payload = { | ||
type: "script_function_payload", | ||
function: "0x1::TestCoin::transfer", | ||
type_arguments: [], | ||
arguments: [account2.address().hex(), "717"], | ||
type: 'script_function_payload', | ||
function: '0x1::Coin::transfer', | ||
type_arguments: ['0x1::TestCoin::TestCoin'], | ||
arguments: [account2.address().hex(), '717'], | ||
}; | ||
const txnRequest = yield client.generateTransaction(account1.address(), payload); | ||
const signedTxn = yield client.signTransaction(account1, txnRequest); | ||
const transactionRes = yield client.submitTransaction(signedTxn); | ||
yield client.waitForTransaction(transactionRes.hash); | ||
resources = yield client.getAccountResources(account2.address()); | ||
accountResource = resources.find((r) => r.type === "0x1::TestCoin::Balance"); | ||
expect(accountResource.data.coin.value).toBe("717"); | ||
const res = yield client.getAccountTransactions(account1.address(), { start: 0 }); | ||
const tx = res.find((e) => e.type === "user_transaction"); | ||
const txnRequest = await client.generateTransaction(account1.address(), payload); | ||
const signedTxn = await client.signTransaction(account1, txnRequest); | ||
const transactionRes = await client.submitTransaction(signedTxn); | ||
await client.waitForTransaction(transactionRes.hash); | ||
resources = await client.getAccountResources(account2.address()); | ||
accountResource = resources.find((r) => r.type === '0x1::Coin::CoinStore<0x1::TestCoin::TestCoin>'); | ||
expect(accountResource.data.coin.value).toBe('717'); | ||
const res = await client.getAccountTransactions(account1.address(), { start: 0 }); | ||
const tx = res.find((e) => e.type === 'user_transaction'); | ||
expect(new hex_string_1.HexString(tx.sender).toShortString()).toBe(account1.address().toShortString()); | ||
const events = yield client.getEventsByEventHandle(tx.sender, "0x1::TestCoin::TransferEvents", "sent_events"); | ||
expect(events[0].type).toBe("0x1::TestCoin::SentEvent"); | ||
const event_subset = yield client.getEventsByEventHandle(tx.sender, "0x1::TestCoin::TransferEvents", "sent_events", { start: 0, limit: 1 }); | ||
expect(event_subset[0].type).toBe("0x1::TestCoin::SentEvent"); | ||
const events2 = yield client.getEventsByEventKey(events[0].key); | ||
expect(events2[0].type).toBe("0x1::TestCoin::SentEvent"); | ||
}), 30 * 1000); | ||
const events = await client.getEventsByEventHandle(tx.sender, '0x1::Coin::CoinStore<0x1::TestCoin::TestCoin>', 'withdraw_events'); | ||
expect(events[0].type).toBe('0x1::Coin::WithdrawEvent'); | ||
const eventSubset = await client.getEventsByEventHandle(tx.sender, '0x1::Coin::CoinStore<0x1::TestCoin::TestCoin>', 'withdraw_events', { start: 0, limit: 1 }); | ||
expect(eventSubset[0].type).toBe('0x1::Coin::WithdrawEvent'); | ||
const events2 = await client.getEventsByEventKey(events[0].key); | ||
expect(events2[0].type).toBe('0x1::Coin::WithdrawEvent'); | ||
}, 30 * 1000); | ||
//# sourceMappingURL=faucet_client.test.js.map |
@@ -1,3 +0,3 @@ | ||
import { Buffer } from "buffer/"; | ||
import { Types } from "./types"; | ||
import { Buffer } from 'buffer/'; | ||
import { Types } from './types'; | ||
export declare type MaybeHexString = HexString | string | Types.HexEncodedBytes; | ||
@@ -4,0 +4,0 @@ export declare class HexString { |
@@ -7,3 +7,3 @@ "use strict"; | ||
constructor(hexString) { | ||
if (hexString.startsWith("0x")) { | ||
if (hexString.startsWith('0x')) { | ||
this.hexString = hexString; | ||
@@ -16,3 +16,3 @@ } | ||
static fromBuffer(buffer) { | ||
return new HexString(buffer.toString("hex")); | ||
return new HexString(buffer.toString('hex')); | ||
} | ||
@@ -23,3 +23,3 @@ static fromUint8Array(arr) { | ||
static ensure(hexString) { | ||
if (typeof hexString === "string") { | ||
if (typeof hexString === 'string') { | ||
return new HexString(hexString); | ||
@@ -39,7 +39,7 @@ } | ||
toShortString() { | ||
const trimmed = this.hexString.replace(/^0x0*/, ""); | ||
const trimmed = this.hexString.replace(/^0x0*/, ''); | ||
return `0x${trimmed}`; | ||
} | ||
toBuffer() { | ||
return buffer_1.Buffer.from(this.noPrefix(), "hex"); | ||
return buffer_1.Buffer.from(this.noPrefix(), 'hex'); | ||
} | ||
@@ -46,0 +46,0 @@ toUint8Array() { |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
const hex_string_1 = require("./hex_string"); | ||
const withoutPrefix = "007711b4d0"; | ||
const withoutPrefix = '007711b4d0'; | ||
const withPrefix = `0x${withoutPrefix}`; | ||
@@ -12,24 +12,24 @@ function validate(hexString) { | ||
} | ||
test("from/to buffer", () => { | ||
test('from/to buffer', () => { | ||
const hs = new hex_string_1.HexString(withPrefix); | ||
expect(hs.toBuffer().toString("hex")).toBe(withoutPrefix); | ||
expect(hs.toBuffer().toString('hex')).toBe(withoutPrefix); | ||
expect(hex_string_1.HexString.fromBuffer(hs.toBuffer()).hex()).toBe(withPrefix); | ||
}); | ||
test("from/to Uint8Array", () => { | ||
test('from/to Uint8Array', () => { | ||
const hs = new hex_string_1.HexString(withoutPrefix); | ||
expect(hex_string_1.HexString.fromUint8Array(hs.toUint8Array()).hex()).toBe(withPrefix); | ||
}); | ||
test("accepts input without prefix", () => { | ||
test('accepts input without prefix', () => { | ||
const hs = new hex_string_1.HexString(withoutPrefix); | ||
validate(hs); | ||
}); | ||
test("accepts input with prefix", () => { | ||
test('accepts input with prefix', () => { | ||
const hs = new hex_string_1.HexString(withPrefix); | ||
validate(hs); | ||
}); | ||
test("ensures input when string", () => { | ||
test('ensures input when string', () => { | ||
const hs = hex_string_1.HexString.ensure(withoutPrefix); | ||
validate(hs); | ||
}); | ||
test("ensures input when HexString", () => { | ||
test('ensures input when HexString', () => { | ||
const hs1 = new hex_string_1.HexString(withPrefix); | ||
@@ -39,8 +39,8 @@ const hs = hex_string_1.HexString.ensure(hs1); | ||
}); | ||
test("short address form correct", () => { | ||
test('short address form correct', () => { | ||
const hs1 = new hex_string_1.HexString(withoutPrefix); | ||
expect(hs1.toShortString()).toBe(`0x7711b4d0`); | ||
const hs2 = new hex_string_1.HexString("0x2185b82cef9bc46249ff2dbc56c265f6a0e3bdb7b9498cc45e4f6e429530fdc0"); | ||
expect(hs2.toShortString()).toBe(`0x2185b82cef9bc46249ff2dbc56c265f6a0e3bdb7b9498cc45e4f6e429530fdc0`); | ||
expect(hs1.toShortString()).toBe('0x7711b4d0'); | ||
const hs2 = new hex_string_1.HexString('0x2185b82cef9bc46249ff2dbc56c265f6a0e3bdb7b9498cc45e4f6e429530fdc0'); | ||
expect(hs2.toShortString()).toBe('0x2185b82cef9bc46249ff2dbc56c265f6a0e3bdb7b9498cc45e4f6e429530fdc0'); | ||
}); | ||
//# sourceMappingURL=hex_string.test.js.map |
@@ -1,7 +0,7 @@ | ||
export * from "./aptos_account"; | ||
export * from "./hex_string"; | ||
export * from "./aptos_client"; | ||
export * from "./faucet_client"; | ||
export * from "./token_client"; | ||
export * from "./types"; | ||
export * from './aptos_account'; | ||
export * from './hex_string'; | ||
export * from './aptos_client'; | ||
export * from './faucet_client'; | ||
export * from './token_client'; | ||
export * from './types'; | ||
//# sourceMappingURL=index.d.ts.map |
@@ -1,5 +0,5 @@ | ||
import { AptosAccount } from "./aptos_account"; | ||
import { AptosClient } from "./aptos_client"; | ||
import { Types } from "./types"; | ||
import { MaybeHexString } from "./hex_string"; | ||
import { AptosAccount } from './aptos_account'; | ||
import { AptosClient } from './aptos_client'; | ||
import { Types } from './types'; | ||
import { MaybeHexString } from './hex_string'; | ||
export declare class TokenClient { | ||
@@ -6,0 +6,0 @@ aptosClient: AptosClient; |
"use strict"; | ||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||
return new (P || (P = Promise))(function (resolve, reject) { | ||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } | ||
step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||
}); | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
@@ -17,147 +8,129 @@ exports.TokenClient = void 0; | ||
} | ||
submitTransactionHelper(account, payload) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const txnRequest = yield this.aptosClient.generateTransaction(account.address(), payload, { | ||
max_gas_amount: "4000", | ||
}); | ||
const signedTxn = yield this.aptosClient.signTransaction(account, txnRequest); | ||
const res = yield this.aptosClient.submitTransaction(signedTxn); | ||
yield this.aptosClient.waitForTransaction(res.hash); | ||
return Promise.resolve(res.hash); | ||
async submitTransactionHelper(account, payload) { | ||
const txnRequest = await this.aptosClient.generateTransaction(account.address(), payload, { | ||
max_gas_amount: '4000', | ||
}); | ||
const signedTxn = await this.aptosClient.signTransaction(account, txnRequest); | ||
const res = await this.aptosClient.submitTransaction(signedTxn); | ||
await this.aptosClient.waitForTransaction(res.hash); | ||
return Promise.resolve(res.hash); | ||
} | ||
// Creates a new collection within the specified account | ||
createCollection(account, name, description, uri) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const payload = { | ||
type: "script_function_payload", | ||
function: "0x1::Token::create_unlimited_collection_script", | ||
type_arguments: [], | ||
arguments: [ | ||
Buffer.from(name).toString("hex"), | ||
Buffer.from(description).toString("hex"), | ||
Buffer.from(uri).toString("hex"), | ||
], | ||
}; | ||
const transactionHash = yield this.submitTransactionHelper(account, payload); | ||
return transactionHash; | ||
}); | ||
async createCollection(account, name, description, uri) { | ||
const payload = { | ||
type: 'script_function_payload', | ||
function: '0x1::Token::create_unlimited_collection_script', | ||
type_arguments: [], | ||
arguments: [ | ||
Buffer.from(name).toString('hex'), | ||
Buffer.from(description).toString('hex'), | ||
Buffer.from(uri).toString('hex'), | ||
], | ||
}; | ||
const transactionHash = await this.submitTransactionHelper(account, payload); | ||
return transactionHash; | ||
} | ||
// Creates a new token within the specified account | ||
createToken(account, collectionName, name, description, supply, uri) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const payload = { | ||
type: "script_function_payload", | ||
function: "0x1::Token::create_unlimited_token_script", | ||
type_arguments: [], | ||
arguments: [ | ||
Buffer.from(collectionName).toString("hex"), | ||
Buffer.from(name).toString("hex"), | ||
Buffer.from(description).toString("hex"), | ||
true, | ||
supply.toString(), | ||
Buffer.from(uri).toString("hex"), | ||
], | ||
}; | ||
const transactionHash = yield this.submitTransactionHelper(account, payload); | ||
return transactionHash; | ||
}); | ||
async createToken(account, collectionName, name, description, supply, uri) { | ||
const payload = { | ||
type: 'script_function_payload', | ||
function: '0x1::Token::create_unlimited_token_script', | ||
type_arguments: [], | ||
arguments: [ | ||
Buffer.from(collectionName).toString('hex'), | ||
Buffer.from(name).toString('hex'), | ||
Buffer.from(description).toString('hex'), | ||
true, | ||
supply.toString(), | ||
Buffer.from(uri).toString('hex'), | ||
], | ||
}; | ||
const transactionHash = await this.submitTransactionHelper(account, payload); | ||
return transactionHash; | ||
} | ||
// Offer token to another account | ||
offerToken(account, receiver, creator, collectionName, name, amount) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const payload = { | ||
type: "script_function_payload", | ||
function: "0x1::TokenTransfers::offer_script", | ||
type_arguments: [], | ||
arguments: [ | ||
receiver, | ||
creator, | ||
Buffer.from(collectionName).toString("hex"), | ||
Buffer.from(name).toString("hex"), | ||
amount.toString(), | ||
], | ||
}; | ||
const transactionHash = yield this.submitTransactionHelper(account, payload); | ||
return transactionHash; | ||
}); | ||
async offerToken(account, receiver, creator, collectionName, name, amount) { | ||
const payload = { | ||
type: 'script_function_payload', | ||
function: '0x1::TokenTransfers::offer_script', | ||
type_arguments: [], | ||
arguments: [ | ||
receiver, | ||
creator, | ||
Buffer.from(collectionName).toString('hex'), | ||
Buffer.from(name).toString('hex'), | ||
amount.toString(), | ||
], | ||
}; | ||
const transactionHash = await this.submitTransactionHelper(account, payload); | ||
return transactionHash; | ||
} | ||
// Claim token | ||
claimToken(account, sender, creator, collectionName, name) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const payload = { | ||
type: "script_function_payload", | ||
function: "0x1::TokenTransfers::claim_script", | ||
type_arguments: [], | ||
arguments: [sender, creator, Buffer.from(collectionName).toString("hex"), Buffer.from(name).toString("hex")], | ||
}; | ||
const transactionHash = yield this.submitTransactionHelper(account, payload); | ||
return transactionHash; | ||
}); | ||
async claimToken(account, sender, creator, collectionName, name) { | ||
const payload = { | ||
type: 'script_function_payload', | ||
function: '0x1::TokenTransfers::claim_script', | ||
type_arguments: [], | ||
arguments: [sender, creator, Buffer.from(collectionName).toString('hex'), Buffer.from(name).toString('hex')], | ||
}; | ||
const transactionHash = await this.submitTransactionHelper(account, payload); | ||
return transactionHash; | ||
} | ||
// Cancel token | ||
cancelTokenOffer(account, receiver, creator, collectionName, name) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const payload = { | ||
type: "script_function_payload", | ||
function: "0x1::TokenTransfers::cancel_offer_script", | ||
type_arguments: [], | ||
arguments: [receiver, creator, Buffer.from(collectionName).toString("hex"), Buffer.from(name).toString("hex")], | ||
}; | ||
const transactionHash = yield this.submitTransactionHelper(account, payload); | ||
return transactionHash; | ||
}); | ||
async cancelTokenOffer(account, receiver, creator, collectionName, name) { | ||
const payload = { | ||
type: 'script_function_payload', | ||
function: '0x1::TokenTransfers::cancel_offer_script', | ||
type_arguments: [], | ||
arguments: [receiver, creator, Buffer.from(collectionName).toString('hex'), Buffer.from(name).toString('hex')], | ||
}; | ||
const transactionHash = await this.submitTransactionHelper(account, payload); | ||
return transactionHash; | ||
} | ||
getCollectionData(creator, collectionName) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const resources = yield this.aptosClient.getAccountResources(creator); | ||
const accountResource = resources.find((r) => r.type === "0x1::Token::Collections"); | ||
const { handle } = accountResource.data.collections; | ||
const getCollectionTableItemRequest = { | ||
key_type: "0x1::ASCII::String", | ||
value_type: "0x1::Token::Collection", | ||
key: collectionName, | ||
}; | ||
// eslint-disable-next-line no-unused-vars | ||
const collectionTable = yield this.aptosClient.getTableItem(handle, getCollectionTableItemRequest); | ||
return collectionTable; | ||
}); | ||
async getCollectionData(creator, collectionName) { | ||
const resources = await this.aptosClient.getAccountResources(creator); | ||
const accountResource = resources.find((r) => r.type === '0x1::Token::Collections'); | ||
const { handle } = accountResource.data.collections; | ||
const getCollectionTableItemRequest = { | ||
key_type: '0x1::ASCII::String', | ||
value_type: '0x1::Token::Collection', | ||
key: collectionName, | ||
}; | ||
// eslint-disable-next-line no-unused-vars | ||
const collectionTable = await this.aptosClient.getTableItem(handle, getCollectionTableItemRequest); | ||
return collectionTable; | ||
} | ||
// Retrieve the token's creation_num, which is useful for non-creator operations | ||
getTokenData(creator, collectionName, tokenName) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const collection = yield this.aptosClient.getAccountResource(creator, "0x1::Token::Collections"); | ||
const { handle } = collection.data.token_data; | ||
const tokenId = { | ||
creator, | ||
collection: collectionName, | ||
name: tokenName, | ||
}; | ||
const getTokenTableItemRequest = { | ||
key_type: "0x1::Token::TokenId", | ||
value_type: "0x1::Token::TokenData", | ||
key: tokenId, | ||
}; | ||
const tableItem = yield this.aptosClient.getTableItem(handle, getTokenTableItemRequest); | ||
return tableItem; | ||
}); | ||
async getTokenData(creator, collectionName, tokenName) { | ||
const collection = await this.aptosClient.getAccountResource(creator, '0x1::Token::Collections'); | ||
const { handle } = collection.data.token_data; | ||
const tokenId = { | ||
creator, | ||
collection: collectionName, | ||
name: tokenName, | ||
}; | ||
const getTokenTableItemRequest = { | ||
key_type: '0x1::Token::TokenId', | ||
value_type: '0x1::Token::TokenData', | ||
key: tokenId, | ||
}; | ||
const tableItem = await this.aptosClient.getTableItem(handle, getTokenTableItemRequest); | ||
return tableItem; | ||
} | ||
// Retrieve the token's creation_num, which is useful for non-creator operations | ||
getTokenBalance(creator, collectionName, tokenName) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const tokenStore = yield this.aptosClient.getAccountResource(creator, "0x1::Token::TokenStore"); | ||
const { handle } = tokenStore.data.tokens; | ||
const tokenId = { | ||
creator, | ||
collection: collectionName, | ||
name: tokenName, | ||
}; | ||
const getTokenTableItemRequest = { | ||
key_type: "0x1::Token::TokenId", | ||
value_type: "0x1::Token::Token", | ||
key: tokenId, | ||
}; | ||
const tableItem = yield this.aptosClient.getTableItem(handle, getTokenTableItemRequest); | ||
return tableItem; | ||
}); | ||
async getTokenBalance(creator, collectionName, tokenName) { | ||
const tokenStore = await this.aptosClient.getAccountResource(creator, '0x1::Token::TokenStore'); | ||
const { handle } = tokenStore.data.tokens; | ||
const tokenId = { | ||
creator, | ||
collection: collectionName, | ||
name: tokenName, | ||
}; | ||
const getTokenTableItemRequest = { | ||
key_type: '0x1::Token::TokenId', | ||
value_type: '0x1::Token::Token', | ||
key: tokenId, | ||
}; | ||
const tableItem = await this.aptosClient.getTableItem(handle, getTokenTableItemRequest); | ||
return tableItem; | ||
} | ||
@@ -164,0 +137,0 @@ } |
"use strict"; | ||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||
return new (P || (P = Promise))(function (resolve, reject) { | ||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } | ||
step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||
}); | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
@@ -16,5 +7,4 @@ const faucet_client_1 = require("./faucet_client"); | ||
const token_client_1 = require("./token_client"); | ||
// import { Types } from "./types"; | ||
const util_test_1 = require("./util.test"); | ||
test("full tutorial nft token flow", () => __awaiter(void 0, void 0, void 0, function* () { | ||
test('full tutorial nft token flow', async () => { | ||
const client = new aptos_client_1.AptosClient(util_test_1.NODE_URL); | ||
@@ -26,18 +16,21 @@ const faucetClient = new faucet_client_1.FaucetClient(util_test_1.NODE_URL, util_test_1.FAUCET_URL); | ||
// Fund both Alice's and Bob's Account | ||
yield faucetClient.fundAccount(alice.address(), 10000); | ||
yield faucetClient.fundAccount(bob.address(), 5000); | ||
const collection_name = "AliceCollection"; | ||
const token_name = "Alice Token"; | ||
await faucetClient.fundAccount(alice.address(), 10000); | ||
await faucetClient.fundAccount(bob.address(), 5000); | ||
const collectionName = 'AliceCollection'; | ||
const tokenName = 'Alice Token'; | ||
// Create collection and token on Alice's account | ||
yield tokenClient.createCollection(alice, collection_name, "Alice's simple collection", "https://aptos.dev"); | ||
yield tokenClient.createToken(alice, collection_name, token_name, "Alice's simple token", 1, "https://aptos.dev/img/nyan.jpeg"); | ||
// eslint-disable-next-line quotes | ||
await tokenClient.createCollection(alice, collectionName, "Alice's simple collection", 'https://aptos.dev'); | ||
await tokenClient.createToken(alice, collectionName, tokenName, | ||
// eslint-disable-next-line quotes | ||
"Alice's simple token", 1, 'https://aptos.dev/img/nyan.jpeg'); | ||
// Transfer Token from Alice's Account to Bob's Account | ||
yield tokenClient.getCollectionData(alice.address().hex(), collection_name); | ||
yield tokenClient.getTokenBalance(alice.address().hex(), collection_name, token_name); | ||
yield tokenClient.getTokenData(alice.address().hex(), collection_name, token_name); | ||
yield tokenClient.offerToken(alice, bob.address().hex(), alice.address().hex(), collection_name, token_name, 1); | ||
yield tokenClient.cancelTokenOffer(alice, bob.address().hex(), alice.address().hex(), collection_name, token_name); | ||
yield tokenClient.offerToken(alice, bob.address().hex(), alice.address().hex(), collection_name, token_name, 1); | ||
yield tokenClient.claimToken(bob, alice.address().hex(), alice.address().hex(), collection_name, token_name); | ||
}), 30 * 1000); | ||
await tokenClient.getCollectionData(alice.address().hex(), collectionName); | ||
await tokenClient.getTokenBalance(alice.address().hex(), collectionName, tokenName); | ||
await tokenClient.getTokenData(alice.address().hex(), collectionName, tokenName); | ||
await tokenClient.offerToken(alice, bob.address().hex(), alice.address().hex(), collectionName, tokenName, 1); | ||
await tokenClient.cancelTokenOffer(alice, bob.address().hex(), alice.address().hex(), collectionName, tokenName); | ||
await tokenClient.offerToken(alice, bob.address().hex(), alice.address().hex(), collectionName, tokenName, 1); | ||
await tokenClient.claimToken(bob, alice.address().hex(), alice.address().hex(), collectionName, tokenName); | ||
}, 30 * 1000); | ||
//# sourceMappingURL=token_client.test.js.map |
@@ -1,3 +0,3 @@ | ||
import * as Types from "./api/data-contracts"; | ||
import * as Types from './api/data-contracts'; | ||
export { Types }; | ||
//# sourceMappingURL=types.d.ts.map |
"use strict"; | ||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||
return new (P || (P = Promise))(function (resolve, reject) { | ||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } | ||
step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||
}); | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.sleep = void 0; | ||
function sleep(timeMs) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
return new Promise((resolve) => { | ||
setTimeout(resolve, timeMs); | ||
}); | ||
async function sleep(timeMs) { | ||
return new Promise((resolve) => { | ||
setTimeout(resolve, timeMs); | ||
}); | ||
@@ -19,0 +8,0 @@ } |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.FAUCET_URL = exports.NODE_URL = void 0; | ||
exports.NODE_URL = process.env.APTOS_NODE_URL || "https://fullnode.devnet.aptoslabs.com"; | ||
exports.FAUCET_URL = process.env.APTOS_FAUCET_URL || "https://faucet.devnet.aptoslabs.com"; | ||
test("noop", () => { | ||
exports.NODE_URL = process.env.APTOS_NODE_URL || 'https://fullnode.devnet.aptoslabs.com'; | ||
exports.FAUCET_URL = process.env.APTOS_FAUCET_URL || 'https://faucet.devnet.aptoslabs.com'; | ||
test('noop', () => { | ||
// All TS files are compiled by default into the npm package | ||
@@ -8,0 +8,0 @@ // Adding this empty test allows us to: |
@@ -1,5 +0,5 @@ | ||
const aptos = require("aptos"); | ||
const aptos = require('aptos'); | ||
const NODE_URL = process.env.APTOS_NODE_URL || "https://fullnode.devnet.aptoslabs.com"; | ||
const FAUCET_URL = process.env.APTOS_FAUCET_URL || "https://faucet.devnet.aptoslabs.com"; | ||
const NODE_URL = process.env.APTOS_NODE_URL || 'https://fullnode.devnet.aptoslabs.com'; | ||
const FAUCET_URL = process.env.APTOS_FAUCET_URL || 'https://faucet.devnet.aptoslabs.com'; | ||
@@ -13,3 +13,3 @@ (async () => { | ||
let resources = await client.getAccountResources(account1.address()); | ||
let accountResource = resources.find((r) => r.type === "0x1::TestCoin::Balance"); | ||
let accountResource = resources.find((r) => r.type === '0x1::Coin::CoinStore<0x1::TestCoin::TestCoin>'); | ||
console.log(`account2 coins: ${accountResource.data.coin.value}. Should be 5000!`); | ||
@@ -20,10 +20,10 @@ | ||
resources = await client.getAccountResources(account2.address()); | ||
accountResource = resources.find((r) => r.type === "0x1::TestCoin::Balance"); | ||
accountResource = resources.find((r) => r.type === '0x1::Coin::CoinStore<0x1::TestCoin::TestCoin>'); | ||
console.log(`account2 coins: ${accountResource.data.coin.value}. Should be 0!`); | ||
const payload = { | ||
type: "script_function_payload", | ||
function: "0x1::TestCoin::transfer", | ||
type_arguments: [], | ||
arguments: [account2.address().hex(), "717"], | ||
type: 'script_function_payload', | ||
function: '0x1::Coin::transfer', | ||
type_arguments: ['0x1::TestCoin::TestCoin'], | ||
arguments: [account2.address().hex(), '717'], | ||
}; | ||
@@ -36,4 +36,4 @@ const txnRequest = await client.generateTransaction(account1.address(), payload); | ||
resources = await client.getAccountResources(account2.address()); | ||
accountResource = resources.find((r) => r.type === "0x1::TestCoin::Balance"); | ||
accountResource = resources.find((r) => r.type === '0x1::Coin::CoinStore<0x1::TestCoin::TestCoin>'); | ||
console.log(`account2 coins: ${accountResource.data.coin.value}. Should be 717!`); | ||
})(); |
@@ -1,5 +0,6 @@ | ||
import { AptosClient, AptosAccount, FaucetClient, Types } from "aptos"; | ||
/* eslint-disable no-console */ | ||
import { AptosClient, AptosAccount, FaucetClient, Types } from 'aptos'; | ||
const NODE_URL = process.env.APTOS_NODE_URL || "https://fullnode.devnet.aptoslabs.com"; | ||
const FAUCET_URL = process.env.APTOS_FAUCET_URL || "https://faucet.devnet.aptoslabs.com"; | ||
const NODE_URL = process.env.APTOS_NODE_URL || 'https://fullnode.devnet.aptoslabs.com'; | ||
const FAUCET_URL = process.env.APTOS_FAUCET_URL || 'https://faucet.devnet.aptoslabs.com'; | ||
@@ -13,3 +14,3 @@ (async () => { | ||
let resources = await client.getAccountResources(account1.address()); | ||
let accountResource = resources.find((r) => r.type === "0x1::TestCoin::Balance"); | ||
let accountResource = resources.find((r) => r.type === '0x1::Coin::CoinStore<0x1::TestCoin::TestCoin>'); | ||
let balance = (accountResource.data as { coin: { value: string } }).coin.value; | ||
@@ -21,3 +22,3 @@ console.log(`account2 coins: ${balance}. Should be 5000!`); | ||
resources = await client.getAccountResources(account2.address()); | ||
accountResource = resources.find((r) => r.type === "0x1::TestCoin::Balance"); | ||
accountResource = resources.find((r) => r.type === '0x1::Coin::CoinStore<0x1::TestCoin::TestCoin>'); | ||
balance = (accountResource.data as { coin: { value: string } }).coin.value; | ||
@@ -27,6 +28,6 @@ console.log(`account2 coins: ${balance}. Should be 0!`); | ||
const payload: Types.TransactionPayload = { | ||
type: "script_function_payload", | ||
function: "0x1::TestCoin::transfer", | ||
type_arguments: [], | ||
arguments: [account2.address().hex(), "717"], | ||
type: 'script_function_payload', | ||
function: '0x1::Coin::transfer', | ||
type_arguments: ['0x1::TestCoin::TestCoin'], | ||
arguments: [account2.address().hex(), '717'], | ||
}; | ||
@@ -39,5 +40,5 @@ const txnRequest = await client.generateTransaction(account1.address(), payload); | ||
resources = await client.getAccountResources(account2.address()); | ||
accountResource = resources.find((r) => r.type === "0x1::TestCoin::Balance"); | ||
accountResource = resources.find((r) => r.type === '0x1::Coin::CoinStore<0x1::TestCoin::TestCoin>'); | ||
balance = (accountResource.data as { coin: { value: string } }).coin.value; | ||
console.log(`account2 coins: ${balance}. Should be 717!`); | ||
})(); |
@@ -5,3 +5,3 @@ /** @type {import("ts-jest/dist/types").InitialOptionsTsJest} */ | ||
testEnvironment: "node", | ||
coveragePathIgnorePatterns: ["api/*"], | ||
coveragePathIgnorePatterns: ["api/*", "transaction_builder/aptos_types/*"], | ||
testPathIgnorePatterns: ["dist/*"], | ||
@@ -8,0 +8,0 @@ collectCoverage: true, |
@@ -15,3 +15,3 @@ { | ||
"test": "jest", | ||
"_fmt": "prettier --config .prettierrc 'src/**/*.ts' 'examples/**/*.js' 'examples/**/*.ts'", | ||
"_fmt": "prettier 'src/**/*.ts' 'examples/**/*.js' 'examples/**/*.ts'", | ||
"fmt": "yarn _fmt --write", | ||
@@ -42,2 +42,3 @@ "fmt:check": "yarn _fmt --check", | ||
"eslint-config-airbnb-base": "^15.0.0", | ||
"eslint-config-airbnb-typescript": "^17.0.0", | ||
"eslint-plugin-import": "^2.25.4", | ||
@@ -58,3 +59,3 @@ "jest": "^27.5.1", | ||
}, | ||
"version": "0.0.20" | ||
"version": "1.0.0" | ||
} |
@@ -44,3 +44,3 @@ # Aptos TS/JS SDK | ||
```bash | ||
$ npx swagger-typescript-api -p ../../../api/doc/openapi.yaml -o ./src/api --modular --axios --single-http-client | ||
$ npx swagger-typescript-api@latest -p ../../../api/doc/openapi.yaml -o ./src/api --modular --axios --single-http-client | ||
``` | ||
@@ -47,0 +47,0 @@ |
@@ -452,3 +452,3 @@ /* eslint-disable */ | ||
/** @example XDX */ | ||
gas_currency_code: string; | ||
gas_currency_code?: string; | ||
@@ -463,2 +463,4 @@ /** | ||
export type UserCreateSigningMessageRequest = UserTransactionRequest & { secondary_signers?: Address[] }; | ||
/** | ||
@@ -471,3 +473,8 @@ * This schema is used for appending `signature` field to another schema. | ||
export type Transaction = PendingTransaction | GenesisTransaction | UserTransaction | BlockMetadataTransaction; | ||
export type Transaction = | ||
| PendingTransaction | ||
| GenesisTransaction | ||
| UserTransaction | ||
| BlockMetadataTransaction | ||
| StateCheckpointTransaction; | ||
@@ -479,3 +486,7 @@ export type SubmitTransactionRequest = UserTransactionRequest & UserTransactionSignature; | ||
export type OnChainTransaction = GenesisTransaction | UserTransaction | BlockMetadataTransaction; | ||
export type OnChainTransaction = | ||
| GenesisTransaction | ||
| UserTransaction | ||
| BlockMetadataTransaction | ||
| StateCheckpointTransaction; | ||
@@ -551,2 +562,4 @@ export interface OnChainTransactionInfo { | ||
export type StateCheckpointTransaction = { type: string; timestamp: TimestampUsec } & OnChainTransactionInfo; | ||
export type TransactionPayload = ScriptFunctionPayload | ScriptPayload | ModuleBundlePayload | WriteSetPayload; | ||
@@ -795,4 +808,25 @@ | ||
/** Table item write */ | ||
data: { handle: HexEncodedBytes; key: HexEncodedBytes; value: HexEncodedBytes }; | ||
/** | ||
* All bytes data are represented as hex-encoded string prefixed with `0x` and fulfilled with | ||
* two hex digits per byte. | ||
* | ||
* Different with `Address` type, hex-encoded bytes should not trim any zeros. | ||
*/ | ||
handle: HexEncodedBytes; | ||
/** | ||
* All bytes data are represented as hex-encoded string prefixed with `0x` and fulfilled with | ||
* two hex digits per byte. | ||
* | ||
* Different with `Address` type, hex-encoded bytes should not trim any zeros. | ||
*/ | ||
key: HexEncodedBytes; | ||
/** | ||
* All bytes data are represented as hex-encoded string prefixed with `0x` and fulfilled with | ||
* two hex digits per byte. | ||
* | ||
* Different with `Address` type, hex-encoded bytes should not trim any zeros. | ||
*/ | ||
value: HexEncodedBytes; | ||
} | ||
@@ -799,0 +833,0 @@ |
@@ -111,3 +111,2 @@ /* eslint-disable */ | ||
// @ts-ignore | ||
if (type === ContentType.FormData && body && body !== null && typeof body === "object") { | ||
@@ -114,0 +113,0 @@ // @ts-ignore |
@@ -19,3 +19,3 @@ /* eslint-disable */ | ||
Transaction, | ||
UserTransactionRequest, | ||
UserCreateSigningMessageRequest, | ||
} from "./data-contracts"; | ||
@@ -87,3 +87,3 @@ import { ContentType, HttpClient, RequestParams } from "./http-client"; | ||
*/ | ||
createSigningMessage = (data: UserTransactionRequest, params: RequestParams = {}) => | ||
createSigningMessage = (data: UserCreateSigningMessageRequest, params: RequestParams = {}) => | ||
this.http.request<{ message: HexEncodedBytes }, AptosError>({ | ||
@@ -90,0 +90,0 @@ path: `/transactions/signing_message`, |
@@ -1,11 +0,12 @@ | ||
import { AptosAccount, AptosAccountObject } from "./aptos_account"; | ||
import { AptosAccount, AptosAccountObject } from './aptos_account'; | ||
const AptosAccountObject: AptosAccountObject = { | ||
address: "0x978c213990c4833df71548df7ce49d54c759d6b6d932de22b24d56060b7af2aa", | ||
const aptosAccountObject: AptosAccountObject = { | ||
address: '0x978c213990c4833df71548df7ce49d54c759d6b6d932de22b24d56060b7af2aa', | ||
privateKeyHex: | ||
"0xc5338cd251c22daa8c9c9cc94f498cc8a5c7e1d2e75287a5dda91096fe64efa5de19e5d1880cac87d57484ce9ed2e84cf0f9599f12e7cc3a52e4e7657a763f2c", | ||
publicKeyHex: "0xde19e5d1880cac87d57484ce9ed2e84cf0f9599f12e7cc3a52e4e7657a763f2c", | ||
// eslint-disable-next-line max-len | ||
'0xc5338cd251c22daa8c9c9cc94f498cc8a5c7e1d2e75287a5dda91096fe64efa5de19e5d1880cac87d57484ce9ed2e84cf0f9599f12e7cc3a52e4e7657a763f2c', | ||
publicKeyHex: '0xde19e5d1880cac87d57484ce9ed2e84cf0f9599f12e7cc3a52e4e7657a763f2c', | ||
}; | ||
test("generates random accounts", () => { | ||
test('generates random accounts', () => { | ||
const a1 = new AptosAccount(); | ||
@@ -17,4 +18,4 @@ const a2 = new AptosAccount(); | ||
test("accepts custom address", () => { | ||
const address = "0x777"; | ||
test('accepts custom address', () => { | ||
const address = '0x777'; | ||
const a1 = new AptosAccount(null, address); | ||
@@ -24,16 +25,16 @@ expect(a1.address().hex()).toBe(address); | ||
test("Deserializes from AptosAccountObject", () => { | ||
const a1 = AptosAccount.fromAptosAccountObject(AptosAccountObject); | ||
expect(a1.address().hex()).toBe(AptosAccountObject.address); | ||
expect(a1.pubKey().hex()).toBe(AptosAccountObject.publicKeyHex); | ||
test('Deserializes from AptosAccountObject', () => { | ||
const a1 = AptosAccount.fromAptosAccountObject(aptosAccountObject); | ||
expect(a1.address().hex()).toBe(aptosAccountObject.address); | ||
expect(a1.pubKey().hex()).toBe(aptosAccountObject.publicKeyHex); | ||
}); | ||
test("Deserializes from AptosAccountObject without address", () => { | ||
const privateKeyObject = { privateKeyHex: AptosAccountObject.privateKeyHex }; | ||
test('Deserializes from AptosAccountObject without address', () => { | ||
const privateKeyObject = { privateKeyHex: aptosAccountObject.privateKeyHex }; | ||
const a1 = AptosAccount.fromAptosAccountObject(privateKeyObject); | ||
expect(a1.address().hex()).toBe(AptosAccountObject.address); | ||
expect(a1.pubKey().hex()).toBe(AptosAccountObject.publicKeyHex); | ||
expect(a1.address().hex()).toBe(aptosAccountObject.address); | ||
expect(a1.pubKey().hex()).toBe(aptosAccountObject.publicKeyHex); | ||
}); | ||
test("Serializes/Deserializes", () => { | ||
test('Serializes/Deserializes', () => { | ||
const a1 = new AptosAccount(); | ||
@@ -45,7 +46,8 @@ const a2 = AptosAccount.fromAptosAccountObject(a1.toPrivateKeyObject()); | ||
test("Signs Strings", () => { | ||
const a1 = AptosAccount.fromAptosAccountObject(AptosAccountObject); | ||
expect(a1.signHexString("0x77777").hex()).toBe( | ||
"0xc5de9e40ac00b371cd83b1c197fa5b665b7449b33cd3cdd305bb78222e06a671a49625ab9aea8a039d4bb70e275768084d62b094bc1b31964f2357b7c1af7e0d", | ||
test('Signs Strings', () => { | ||
const a1 = AptosAccount.fromAptosAccountObject(aptosAccountObject); | ||
expect(a1.signHexString('0x77777').hex()).toBe( | ||
// eslint-disable-next-line max-len | ||
'0xc5de9e40ac00b371cd83b1c197fa5b665b7449b33cd3cdd305bb78222e06a671a49625ab9aea8a039d4bb70e275768084d62b094bc1b31964f2357b7c1af7e0d', | ||
); | ||
}); |
@@ -1,6 +0,6 @@ | ||
import * as Nacl from "tweetnacl"; | ||
import * as SHA3 from "js-sha3"; | ||
import { Buffer } from "buffer/"; // the trailing slash is important! | ||
import { HexString, MaybeHexString } from "./hex_string"; | ||
import { Types } from "./types"; | ||
import * as Nacl from 'tweetnacl'; | ||
import * as SHA3 from 'js-sha3'; | ||
import { Buffer } from 'buffer/'; // the trailing slash is important! | ||
import { HexString, MaybeHexString } from './hex_string'; | ||
import { Types } from './types'; | ||
@@ -45,3 +45,3 @@ export interface AptosAccountObject { | ||
hash.update(Buffer.from(this.signingKey.publicKey)); | ||
hash.update("\x00"); | ||
hash.update('\x00'); | ||
this.authKeyCached = new HexString(hash.hex()); | ||
@@ -54,3 +54,3 @@ } | ||
pubKey(): HexString { | ||
return HexString.ensure(Buffer.from(this.signingKey.publicKey).toString("hex")); | ||
return HexString.ensure(Buffer.from(this.signingKey.publicKey).toString('hex')); | ||
} | ||
@@ -60,3 +60,3 @@ | ||
const signature = Nacl.sign(buffer, this.signingKey.secretKey); | ||
return HexString.ensure(Buffer.from(signature).toString("hex").slice(0, 128)); | ||
return HexString.ensure(Buffer.from(signature).toString('hex').slice(0, 128)); | ||
} | ||
@@ -63,0 +63,0 @@ |
@@ -1,10 +0,22 @@ | ||
import { AptosClient, raiseForStatus } from "./aptos_client"; | ||
import { AnyObject } from "./util"; | ||
import { AxiosResponse } from "axios"; | ||
import { AxiosResponse } from 'axios'; | ||
import { AptosClient, raiseForStatus } from './aptos_client'; | ||
import { AnyObject } from './util'; | ||
import { NODE_URL } from "./util.test"; | ||
import { FAUCET_URL, NODE_URL } from './util.test'; | ||
import { FaucetClient } from './faucet_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'; | ||
test("gets genesis account", async () => { | ||
test('gets genesis account', async () => { | ||
const client = new AptosClient(NODE_URL); | ||
const account = await client.getAccount("0x1"); | ||
const account = await client.getAccount('0x1'); | ||
expect(account.authentication_key.length).toBe(66); | ||
@@ -14,3 +26,3 @@ expect(account.sequence_number).not.toBeNull(); | ||
test("gets transactions", async () => { | ||
test('gets transactions', async () => { | ||
const client = new AptosClient(NODE_URL); | ||
@@ -21,16 +33,16 @@ const transactions = await client.getTransactions(); | ||
test("gets genesis resources", async () => { | ||
test('gets genesis resources', async () => { | ||
const client = new AptosClient(NODE_URL); | ||
const resources = await client.getAccountResources("0x1"); | ||
const accountResource = resources.find((r) => r.type === "0x1::Account::Account"); | ||
expect((accountResource.data as AnyObject)["self_address"]).toBe("0x1"); | ||
const resources = await client.getAccountResources('0x1'); | ||
const accountResource = resources.find((r) => r.type === '0x1::Account::Account'); | ||
expect((accountResource.data as AnyObject).self_address).toBe('0x1'); | ||
}); | ||
test("gets the Account resource", async () => { | ||
test('gets the Account resource', async () => { | ||
const client = new AptosClient(NODE_URL); | ||
const accountResource = await client.getAccountResource("0x1", "0x1::Account::Account"); | ||
expect((accountResource.data as AnyObject)["self_address"]).toBe("0x1"); | ||
const accountResource = await client.getAccountResource('0x1', '0x1::Account::Account'); | ||
expect((accountResource.data as AnyObject).self_address).toBe('0x1'); | ||
}); | ||
test("gets ledger info", async () => { | ||
test('gets ledger info', async () => { | ||
const client = new AptosClient(NODE_URL); | ||
@@ -42,24 +54,24 @@ const ledgerInfo = await client.getLedgerInfo(); | ||
test("gets account modules", async () => { | ||
test('gets account modules', async () => { | ||
const client = new AptosClient(NODE_URL); | ||
const modules = await client.getAccountModules("0x1"); | ||
const module = modules.find((r) => r.abi.name === "TestCoin"); | ||
expect(module.abi.address).toBe("0x1"); | ||
const modules = await client.getAccountModules('0x1'); | ||
const module = modules.find((r) => r.abi.name === 'TestCoin'); | ||
expect(module.abi.address).toBe('0x1'); | ||
}); | ||
test("gets the TestCoin module", async () => { | ||
test('gets the TestCoin module', async () => { | ||
const client = new AptosClient(NODE_URL); | ||
const module = await client.getAccountModule("0x1", "TestCoin"); | ||
expect(module.abi.address).toBe("0x1"); | ||
const module = await client.getAccountModule('0x1', 'TestCoin'); | ||
expect(module.abi.address).toBe('0x1'); | ||
}); | ||
test("test raiseForStatus", async () => { | ||
const testData = { hello: "wow" }; | ||
test('test raiseForStatus', async () => { | ||
const testData = { hello: 'wow' }; | ||
const fakeResponse: AxiosResponse = { | ||
status: 200, | ||
statusText: "Status Text", | ||
data: "some string", | ||
statusText: 'Status Text', | ||
data: 'some string', | ||
request: { | ||
host: "host", | ||
path: "/path", | ||
host: 'host', | ||
path: '/path', | ||
}, | ||
@@ -86,1 +98,57 @@ } as AxiosResponse; | ||
}); | ||
test( | ||
'submits bcs transaction', | ||
async () => { | ||
const client = new AptosClient(NODE_URL); | ||
const faucetClient = new FaucetClient(NODE_URL, FAUCET_URL, null); | ||
const account1 = new AptosAccount(); | ||
await faucetClient.fundAccount(account1.address(), 5000); | ||
let resources = await client.getAccountResources(account1.address()); | ||
let accountResource = resources.find((r) => r.type === '0x1::Coin::CoinStore<0x1::TestCoin::TestCoin>'); | ||
expect((accountResource.data as any).coin.value).toBe('5000'); | ||
const account2 = new AptosAccount(); | ||
await faucetClient.fundAccount(account2.address(), 0); | ||
resources = await client.getAccountResources(account2.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 TypeTagStruct(StructTag.fromString('0x1::TestCoin::TestCoin')); | ||
const scriptFunctionPayload = new TransactionPayloadScriptFunction( | ||
ScriptFunction.natual( | ||
'0x1::Coin', | ||
'transfer', | ||
[token], | ||
[bcsToBytes(AccountAddress.fromHex(account2.address())), bcsSerializeUint64(717)], | ||
), | ||
); | ||
const [{ sequence_number: sequnceNumber }, chainId] = await Promise.all([ | ||
client.getAccount(account1.address()), | ||
client.getChainId(), | ||
]); | ||
const rawTxn = new RawTransaction( | ||
AccountAddress.fromHex(account1.address()), | ||
BigInt(sequnceNumber), | ||
scriptFunctionPayload, | ||
1000n, | ||
1n, | ||
BigInt(Math.floor(Date.now() / 1000) + 10), | ||
new ChainId(chainId), | ||
); | ||
const bcsTxn = await AptosClient.generateBCSTransaction(account1, rawTxn); | ||
const transactionRes = await client.submitSignedBCSTransaction(bcsTxn); | ||
await client.waitForTransaction(transactionRes.hash); | ||
resources = await client.getAccountResources(account2.address()); | ||
accountResource = resources.find((r) => r.type === '0x1::Coin::CoinStore<0x1::TestCoin::TestCoin>'); | ||
expect((accountResource.data as any).coin.value).toBe('717'); | ||
}, | ||
30 * 1000, | ||
); |
@@ -1,12 +0,14 @@ | ||
import { AxiosRequestConfig, AxiosResponse } from "axios"; | ||
import { Accounts } from "./api/Accounts"; | ||
import { Events } from "./api/Events"; | ||
import { Transactions } from "./api/Transactions"; | ||
import { HttpClient, RequestParams } from "./api/http-client"; | ||
import { HexString, MaybeHexString } from "./hex_string"; | ||
import { sleep } from "./util"; | ||
import { AptosAccount } from "./aptos_account"; | ||
import { Types } from "./types"; | ||
import { Tables } from "./api/Tables"; | ||
import { Address, AptosError, LedgerVersion, MoveModule } from "./api/data-contracts"; | ||
import { AxiosRequestConfig, AxiosResponse } from 'axios'; | ||
import { Accounts } from './api/Accounts'; | ||
import { Events } from './api/Events'; | ||
import { Transactions } from './api/Transactions'; | ||
import { HttpClient, RequestParams } from './api/http-client'; | ||
import { HexString, MaybeHexString } from './hex_string'; | ||
import { sleep } from './util'; | ||
import { AptosAccount } from './aptos_account'; | ||
import { Types } from './types'; | ||
import { Tables } from './api/Tables'; | ||
import { AptosError } from './api/data-contracts'; | ||
import * as TxnBuilderTypes from './transaction_builder/aptos_types'; | ||
import { SigningMessage, TransactionBuilderEd25519 } from './transaction_builder'; | ||
@@ -20,4 +22,4 @@ export class RequestError extends Error { | ||
const data = JSON.stringify(response.data); | ||
const hostAndPath = [response.request?.host, response.request?.path].filter((e) => !!e).join(""); | ||
super(`${message} - ${data}${hostAndPath ? ` @ ${hostAndPath}` : ""}${requestBody ? ` : ${requestBody}` : ""}`); | ||
const hostAndPath = [response.request?.host, response.request?.path].filter((e) => !!e).join(''); | ||
super(`${message} - ${data}${hostAndPath ? ` @ ${hostAndPath}` : ''}${requestBody ? ` : ${requestBody}` : ''}`); | ||
this.response = response; | ||
@@ -29,3 +31,3 @@ this.requestBody = requestBody; | ||
export type AptosClientConfig = Omit<AxiosRequestConfig, "data" | "cancelToken" | "method">; | ||
export type AptosClientConfig = Omit<AxiosRequestConfig, 'data' | 'cancelToken' | 'method'>; | ||
@@ -140,2 +142,17 @@ export function raiseForStatus<T>( | ||
/** 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) => { | ||
// @ts-ignore | ||
const sigHexStr = accountFrom.signBuffer(signingMessage); | ||
return sigHexStr.toUint8Array(); | ||
}, accountFrom.pubKey().toUint8Array()); | ||
const signedTxn = await txnBuilder.sign(rawTxn); | ||
return signedTxn; | ||
} | ||
/** Generates a transaction request that can be submitted to produce a raw transaction that | ||
@@ -153,5 +170,5 @@ * can be signed, which upon being signed can be submitted to the blockchain. */ | ||
sequence_number: account.sequence_number, | ||
max_gas_amount: "1000", | ||
gas_unit_price: "1", | ||
gas_currency_code: "XUS", | ||
max_gas_amount: '1000', | ||
gas_unit_price: '1', | ||
gas_currency_code: 'XUS', | ||
// Unix timestamp, in seconds + 10 seconds | ||
@@ -185,3 +202,3 @@ expiration_timestamp_secs: (Math.floor(Date.now() / 1000) + 10).toString(), | ||
const transactionSignature: Types.TransactionSignature = { | ||
type: "ed25519_signature", | ||
type: 'ed25519_signature', | ||
public_key: accountFrom.pubKey().hex(), | ||
@@ -216,3 +233,3 @@ signature: signatureHex.hex(), | ||
/** Submits a signed transaction to the blockchain. */ | ||
/** Submits a signed transaction to the transaction endpoint that takes JSON payload. */ | ||
async submitTransaction(signedTxnRequest: Types.SubmitTransactionRequest): Promise<Types.PendingTransaction> { | ||
@@ -224,2 +241,20 @@ const response = await this.transactions.submitTransaction(signedTxnRequest); | ||
/** Submits a signed transaction to the the endpoint that takes BCS payload. */ | ||
async submitSignedBCSTransaction(signedTxn: Uint8Array): Promise<Types.PendingTransaction> { | ||
// Need to construct a customized post request for transactions in BCS payload | ||
const httpClient = this.transactions.http; | ||
const response = await httpClient.request<Types.PendingTransaction, AptosError>({ | ||
path: '/transactions', | ||
method: 'POST', | ||
body: signedTxn, | ||
// @ts-ignore | ||
type: 'application/x.aptos.signed_transaction+bcs', | ||
format: 'json', | ||
}); | ||
raiseForStatus(202, response, signedTxn); | ||
return response.data; | ||
} | ||
async getTransactions(query?: { start?: number; limit?: number }): Promise<Types.OnChainTransaction[]> { | ||
@@ -244,3 +279,3 @@ const response = await this.transactions.getTransactions(query); | ||
raiseForStatus(200, response, txnHash); | ||
return response.data.type === "pending_transaction"; | ||
return response.data.type === 'pending_transaction'; | ||
} | ||
@@ -264,5 +299,5 @@ | ||
const result = await this.client.request<Types.LedgerInfo, AptosError>({ | ||
path: "/", | ||
method: "GET", | ||
format: "json", | ||
path: '/', | ||
method: 'GET', | ||
format: 'json', | ||
...params, | ||
@@ -273,2 +308,7 @@ }); | ||
async getChainId(params: RequestParams = {}): Promise<number> { | ||
const result = await this.getLedgerInfo(params); | ||
return result.chain_id; | ||
} | ||
async getTableItem(handle: string, data: Types.TableItemRequest, params?: RequestParams): Promise<any> { | ||
@@ -275,0 +315,0 @@ const tableItem = await this.tables.getTableItem(handle, data, params); |
@@ -1,12 +0,12 @@ | ||
import { AptosClient } from "./aptos_client"; | ||
import { FaucetClient } from "./faucet_client"; | ||
import { AptosAccount } from "./aptos_account"; | ||
import { Types } from "./types"; | ||
import { UserTransaction } from "./api/data-contracts"; | ||
import { HexString } from "./hex_string"; | ||
import { AptosClient } from './aptos_client'; | ||
import { FaucetClient } from './faucet_client'; | ||
import { AptosAccount } from './aptos_account'; | ||
import { Types } from './types'; | ||
import { UserTransaction } from './api/data-contracts'; | ||
import { HexString } from './hex_string'; | ||
import { NODE_URL, FAUCET_URL } from "./util.test"; | ||
import { NODE_URL, FAUCET_URL } from './util.test'; | ||
test( | ||
"full tutorial faucet flow", | ||
'full tutorial faucet flow', | ||
async () => { | ||
@@ -19,6 +19,6 @@ const client = new AptosClient(NODE_URL); | ||
const tx1 = await client.getTransaction(txns[1]); | ||
expect(tx1.type).toBe("user_transaction"); | ||
expect(tx1.type).toBe('user_transaction'); | ||
let resources = await client.getAccountResources(account1.address()); | ||
let accountResource = resources.find((r) => r.type === "0x1::TestCoin::Balance"); | ||
expect((accountResource.data as { coin: { value: string } }).coin.value).toBe("5000"); | ||
let accountResource = resources.find((r) => r.type === '0x1::Coin::CoinStore<0x1::TestCoin::TestCoin>'); | ||
expect((accountResource.data as { coin: { value: string } }).coin.value).toBe('5000'); | ||
@@ -28,10 +28,10 @@ const account2 = new AptosAccount(); | ||
resources = await client.getAccountResources(account2.address()); | ||
accountResource = resources.find((r) => r.type === "0x1::TestCoin::Balance"); | ||
expect((accountResource.data as { coin: { value: string } }).coin.value).toBe("0"); | ||
accountResource = resources.find((r) => r.type === '0x1::Coin::CoinStore<0x1::TestCoin::TestCoin>'); | ||
expect((accountResource.data as { coin: { value: string } }).coin.value).toBe('0'); | ||
const payload: Types.TransactionPayload = { | ||
type: "script_function_payload", | ||
function: "0x1::TestCoin::transfer", | ||
type_arguments: [], | ||
arguments: [account2.address().hex(), "717"], | ||
type: 'script_function_payload', | ||
function: '0x1::Coin::transfer', | ||
type_arguments: ['0x1::TestCoin::TestCoin'], | ||
arguments: [account2.address().hex(), '717'], | ||
}; | ||
@@ -44,24 +44,28 @@ const txnRequest = await client.generateTransaction(account1.address(), payload); | ||
resources = await client.getAccountResources(account2.address()); | ||
accountResource = resources.find((r) => r.type === "0x1::TestCoin::Balance"); | ||
expect((accountResource.data as { coin: { value: string } }).coin.value).toBe("717"); | ||
accountResource = resources.find((r) => r.type === '0x1::Coin::CoinStore<0x1::TestCoin::TestCoin>'); | ||
expect((accountResource.data as { coin: { value: string } }).coin.value).toBe('717'); | ||
const res = await client.getAccountTransactions(account1.address(), { start: 0 }); | ||
const tx = res.find((e) => e.type === "user_transaction") as UserTransaction; | ||
const tx = res.find((e) => e.type === 'user_transaction') as UserTransaction; | ||
expect(new HexString(tx.sender).toShortString()).toBe(account1.address().toShortString()); | ||
const events = await client.getEventsByEventHandle(tx.sender, "0x1::TestCoin::TransferEvents", "sent_events"); | ||
expect(events[0].type).toBe("0x1::TestCoin::SentEvent"); | ||
const events = await client.getEventsByEventHandle( | ||
tx.sender, | ||
'0x1::Coin::CoinStore<0x1::TestCoin::TestCoin>', | ||
'withdraw_events', | ||
); | ||
expect(events[0].type).toBe('0x1::Coin::WithdrawEvent'); | ||
const event_subset = await client.getEventsByEventHandle( | ||
const eventSubset = await client.getEventsByEventHandle( | ||
tx.sender, | ||
"0x1::TestCoin::TransferEvents", | ||
"sent_events", | ||
'0x1::Coin::CoinStore<0x1::TestCoin::TestCoin>', | ||
'withdraw_events', | ||
{ start: 0, limit: 1 }, | ||
); | ||
expect(event_subset[0].type).toBe("0x1::TestCoin::SentEvent"); | ||
expect(eventSubset[0].type).toBe('0x1::Coin::WithdrawEvent'); | ||
const events2 = await client.getEventsByEventKey(events[0].key); | ||
expect(events2[0].type).toBe("0x1::TestCoin::SentEvent"); | ||
expect(events2[0].type).toBe('0x1::Coin::WithdrawEvent'); | ||
}, | ||
30 * 1000, | ||
); |
/** Faucet creates and funds accounts. This is a thin wrapper around that. */ | ||
import axios from "axios"; | ||
import { AptosClient, AptosClientConfig, raiseForStatus } from "./aptos_client"; | ||
import { Types } from "./types"; | ||
import { HexString, MaybeHexString } from "./hex_string"; | ||
import axios from 'axios'; | ||
import { AptosClient, AptosClientConfig, raiseForStatus } from './aptos_client'; | ||
import { Types } from './types'; | ||
import { HexString, MaybeHexString } from './hex_string'; | ||
@@ -7,0 +7,0 @@ export class FaucetClient extends AptosClient { |
@@ -1,4 +0,4 @@ | ||
import { HexString } from "./hex_string"; | ||
import { HexString } from './hex_string'; | ||
const withoutPrefix = "007711b4d0"; | ||
const withoutPrefix = '007711b4d0'; | ||
const withPrefix = `0x${withoutPrefix}`; | ||
@@ -13,9 +13,9 @@ | ||
test("from/to buffer", () => { | ||
test('from/to buffer', () => { | ||
const hs = new HexString(withPrefix); | ||
expect(hs.toBuffer().toString("hex")).toBe(withoutPrefix); | ||
expect(hs.toBuffer().toString('hex')).toBe(withoutPrefix); | ||
expect(HexString.fromBuffer(hs.toBuffer()).hex()).toBe(withPrefix); | ||
}); | ||
test("from/to Uint8Array", () => { | ||
test('from/to Uint8Array', () => { | ||
const hs = new HexString(withoutPrefix); | ||
@@ -25,3 +25,3 @@ expect(HexString.fromUint8Array(hs.toUint8Array()).hex()).toBe(withPrefix); | ||
test("accepts input without prefix", () => { | ||
test('accepts input without prefix', () => { | ||
const hs = new HexString(withoutPrefix); | ||
@@ -31,3 +31,3 @@ validate(hs); | ||
test("accepts input with prefix", () => { | ||
test('accepts input with prefix', () => { | ||
const hs = new HexString(withPrefix); | ||
@@ -37,3 +37,3 @@ validate(hs); | ||
test("ensures input when string", () => { | ||
test('ensures input when string', () => { | ||
const hs = HexString.ensure(withoutPrefix); | ||
@@ -43,3 +43,3 @@ validate(hs); | ||
test("ensures input when HexString", () => { | ||
test('ensures input when HexString', () => { | ||
const hs1 = new HexString(withPrefix); | ||
@@ -50,7 +50,7 @@ const hs = HexString.ensure(hs1); | ||
test("short address form correct", () => { | ||
test('short address form correct', () => { | ||
const hs1 = new HexString(withoutPrefix); | ||
expect(hs1.toShortString()).toBe(`0x7711b4d0`); | ||
const hs2 = new HexString("0x2185b82cef9bc46249ff2dbc56c265f6a0e3bdb7b9498cc45e4f6e429530fdc0"); | ||
expect(hs2.toShortString()).toBe(`0x2185b82cef9bc46249ff2dbc56c265f6a0e3bdb7b9498cc45e4f6e429530fdc0`); | ||
expect(hs1.toShortString()).toBe('0x7711b4d0'); | ||
const hs2 = new HexString('0x2185b82cef9bc46249ff2dbc56c265f6a0e3bdb7b9498cc45e4f6e429530fdc0'); | ||
expect(hs2.toShortString()).toBe('0x2185b82cef9bc46249ff2dbc56c265f6a0e3bdb7b9498cc45e4f6e429530fdc0'); | ||
}); |
@@ -1,3 +0,3 @@ | ||
import { Buffer } from "buffer/"; // the trailing slash is important! | ||
import { Types } from "./types"; | ||
import { Buffer } from 'buffer/'; // the trailing slash is important! | ||
import { Types } from './types'; | ||
@@ -12,3 +12,3 @@ // eslint-disable-next-line no-use-before-define | ||
static fromBuffer(buffer: Buffer): HexString { | ||
return new HexString(buffer.toString("hex")); | ||
return new HexString(buffer.toString('hex')); | ||
} | ||
@@ -21,3 +21,3 @@ | ||
static ensure(hexString: MaybeHexString): HexString { | ||
if (typeof hexString === "string") { | ||
if (typeof hexString === 'string') { | ||
return new HexString(hexString); | ||
@@ -29,3 +29,3 @@ } | ||
constructor(hexString: string | Types.HexEncodedBytes) { | ||
if (hexString.startsWith("0x")) { | ||
if (hexString.startsWith('0x')) { | ||
this.hexString = hexString; | ||
@@ -50,3 +50,3 @@ } else { | ||
toShortString(): string { | ||
const trimmed = this.hexString.replace(/^0x0*/, ""); | ||
const trimmed = this.hexString.replace(/^0x0*/, ''); | ||
return `0x${trimmed}`; | ||
@@ -56,3 +56,3 @@ } | ||
toBuffer(): Buffer { | ||
return Buffer.from(this.noPrefix(), "hex"); | ||
return Buffer.from(this.noPrefix(), 'hex'); | ||
} | ||
@@ -59,0 +59,0 @@ |
// All parts of our package are accessible as imports, but we re-export our higher level API here for convenience | ||
export * from "./aptos_account"; | ||
export * from "./hex_string"; | ||
export * from "./aptos_client"; | ||
export * from "./faucet_client"; | ||
export * from "./token_client"; | ||
export * from "./types"; | ||
export * from './aptos_account'; | ||
export * from './hex_string'; | ||
export * from './aptos_client'; | ||
export * from './faucet_client'; | ||
export * from './token_client'; | ||
export * from './types'; |
@@ -1,11 +0,10 @@ | ||
import { FaucetClient } from "./faucet_client"; | ||
import { AptosAccount } from "./aptos_account"; | ||
import { AptosClient } from "./aptos_client"; | ||
import { TokenClient } from "./token_client"; | ||
// import { Types } from "./types"; | ||
import { FaucetClient } from './faucet_client'; | ||
import { AptosAccount } from './aptos_account'; | ||
import { AptosClient } from './aptos_client'; | ||
import { TokenClient } from './token_client'; | ||
import { NODE_URL, FAUCET_URL } from "./util.test"; | ||
import { NODE_URL, FAUCET_URL } from './util.test'; | ||
test( | ||
"full tutorial nft token flow", | ||
'full tutorial nft token flow', | ||
async () => { | ||
@@ -23,27 +22,29 @@ const client = new AptosClient(NODE_URL); | ||
const collection_name = "AliceCollection"; | ||
const token_name = "Alice Token"; | ||
const collectionName = 'AliceCollection'; | ||
const tokenName = 'Alice Token'; | ||
// Create collection and token on Alice's account | ||
await tokenClient.createCollection(alice, collection_name, "Alice's simple collection", "https://aptos.dev"); | ||
// eslint-disable-next-line quotes | ||
await tokenClient.createCollection(alice, collectionName, "Alice's simple collection", 'https://aptos.dev'); | ||
await tokenClient.createToken( | ||
alice, | ||
collection_name, | ||
token_name, | ||
collectionName, | ||
tokenName, | ||
// eslint-disable-next-line quotes | ||
"Alice's simple token", | ||
1, | ||
"https://aptos.dev/img/nyan.jpeg", | ||
'https://aptos.dev/img/nyan.jpeg', | ||
); | ||
// Transfer Token from Alice's Account to Bob's Account | ||
await tokenClient.getCollectionData(alice.address().hex(), collection_name); | ||
await tokenClient.getTokenBalance(alice.address().hex(), collection_name, token_name); | ||
await tokenClient.getTokenData(alice.address().hex(), collection_name, token_name); | ||
await tokenClient.offerToken(alice, bob.address().hex(), alice.address().hex(), collection_name, token_name, 1); | ||
await tokenClient.cancelTokenOffer(alice, bob.address().hex(), alice.address().hex(), collection_name, token_name); | ||
await tokenClient.offerToken(alice, bob.address().hex(), alice.address().hex(), collection_name, token_name, 1); | ||
await tokenClient.claimToken(bob, alice.address().hex(), alice.address().hex(), collection_name, token_name); | ||
await tokenClient.getCollectionData(alice.address().hex(), collectionName); | ||
await tokenClient.getTokenBalance(alice.address().hex(), collectionName, tokenName); | ||
await tokenClient.getTokenData(alice.address().hex(), collectionName, tokenName); | ||
await tokenClient.offerToken(alice, bob.address().hex(), alice.address().hex(), collectionName, tokenName, 1); | ||
await tokenClient.cancelTokenOffer(alice, bob.address().hex(), alice.address().hex(), collectionName, tokenName); | ||
await tokenClient.offerToken(alice, bob.address().hex(), alice.address().hex(), collectionName, tokenName, 1); | ||
await tokenClient.claimToken(bob, alice.address().hex(), alice.address().hex(), collectionName, tokenName); | ||
}, | ||
30 * 1000, | ||
); |
@@ -1,5 +0,5 @@ | ||
import { AptosAccount } from "./aptos_account"; | ||
import { AptosClient } from "./aptos_client"; | ||
import { Types } from "./types"; | ||
import { MaybeHexString } from "./hex_string"; | ||
import { AptosAccount } from './aptos_account'; | ||
import { AptosClient } from './aptos_client'; | ||
import { Types } from './types'; | ||
import { MaybeHexString } from './hex_string'; | ||
@@ -15,3 +15,3 @@ export class TokenClient { | ||
const txnRequest = await this.aptosClient.generateTransaction(account.address(), payload, { | ||
max_gas_amount: "4000", | ||
max_gas_amount: '4000', | ||
}); | ||
@@ -32,9 +32,9 @@ const signedTxn = await this.aptosClient.signTransaction(account, txnRequest); | ||
const payload: Types.TransactionPayload = { | ||
type: "script_function_payload", | ||
function: "0x1::Token::create_unlimited_collection_script", | ||
type: 'script_function_payload', | ||
function: '0x1::Token::create_unlimited_collection_script', | ||
type_arguments: [], | ||
arguments: [ | ||
Buffer.from(name).toString("hex"), | ||
Buffer.from(description).toString("hex"), | ||
Buffer.from(uri).toString("hex"), | ||
Buffer.from(name).toString('hex'), | ||
Buffer.from(description).toString('hex'), | ||
Buffer.from(uri).toString('hex'), | ||
], | ||
@@ -56,12 +56,12 @@ }; | ||
const payload: Types.TransactionPayload = { | ||
type: "script_function_payload", | ||
function: "0x1::Token::create_unlimited_token_script", | ||
type: 'script_function_payload', | ||
function: '0x1::Token::create_unlimited_token_script', | ||
type_arguments: [], | ||
arguments: [ | ||
Buffer.from(collectionName).toString("hex"), | ||
Buffer.from(name).toString("hex"), | ||
Buffer.from(description).toString("hex"), | ||
Buffer.from(collectionName).toString('hex'), | ||
Buffer.from(name).toString('hex'), | ||
Buffer.from(description).toString('hex'), | ||
true, | ||
supply.toString(), | ||
Buffer.from(uri).toString("hex"), | ||
Buffer.from(uri).toString('hex'), | ||
], | ||
@@ -83,4 +83,4 @@ }; | ||
const payload: Types.TransactionPayload = { | ||
type: "script_function_payload", | ||
function: "0x1::TokenTransfers::offer_script", | ||
type: 'script_function_payload', | ||
function: '0x1::TokenTransfers::offer_script', | ||
type_arguments: [], | ||
@@ -90,4 +90,4 @@ arguments: [ | ||
creator, | ||
Buffer.from(collectionName).toString("hex"), | ||
Buffer.from(name).toString("hex"), | ||
Buffer.from(collectionName).toString('hex'), | ||
Buffer.from(name).toString('hex'), | ||
amount.toString(), | ||
@@ -109,6 +109,6 @@ ], | ||
const payload: Types.TransactionPayload = { | ||
type: "script_function_payload", | ||
function: "0x1::TokenTransfers::claim_script", | ||
type: 'script_function_payload', | ||
function: '0x1::TokenTransfers::claim_script', | ||
type_arguments: [], | ||
arguments: [sender, creator, Buffer.from(collectionName).toString("hex"), Buffer.from(name).toString("hex")], | ||
arguments: [sender, creator, Buffer.from(collectionName).toString('hex'), Buffer.from(name).toString('hex')], | ||
}; | ||
@@ -128,6 +128,6 @@ const transactionHash = await this.submitTransactionHelper(account, payload); | ||
const payload: Types.TransactionPayload = { | ||
type: "script_function_payload", | ||
function: "0x1::TokenTransfers::cancel_offer_script", | ||
type: 'script_function_payload', | ||
function: '0x1::TokenTransfers::cancel_offer_script', | ||
type_arguments: [], | ||
arguments: [receiver, creator, Buffer.from(collectionName).toString("hex"), Buffer.from(name).toString("hex")], | ||
arguments: [receiver, creator, Buffer.from(collectionName).toString('hex'), Buffer.from(name).toString('hex')], | ||
}; | ||
@@ -140,7 +140,7 @@ const transactionHash = await this.submitTransactionHelper(account, payload); | ||
const resources = await this.aptosClient.getAccountResources(creator); | ||
const accountResource: { type: string; data: any } = resources.find((r) => r.type === "0x1::Token::Collections"); | ||
const accountResource: { type: string; data: any } = resources.find((r) => r.type === '0x1::Token::Collections'); | ||
const { handle }: { handle: string } = accountResource.data.collections; | ||
const getCollectionTableItemRequest: Types.TableItemRequest = { | ||
key_type: "0x1::ASCII::String", | ||
value_type: "0x1::Token::Collection", | ||
key_type: '0x1::ASCII::String', | ||
value_type: '0x1::Token::Collection', | ||
key: collectionName, | ||
@@ -157,3 +157,3 @@ }; | ||
creator, | ||
"0x1::Token::Collections", | ||
'0x1::Token::Collections', | ||
); | ||
@@ -168,4 +168,4 @@ const { handle } = collection.data.token_data; | ||
const getTokenTableItemRequest: Types.TableItemRequest = { | ||
key_type: "0x1::Token::TokenId", | ||
value_type: "0x1::Token::TokenData", | ||
key_type: '0x1::Token::TokenId', | ||
value_type: '0x1::Token::TokenData', | ||
key: tokenId, | ||
@@ -182,3 +182,3 @@ }; | ||
creator, | ||
"0x1::Token::TokenStore", | ||
'0x1::Token::TokenStore', | ||
); | ||
@@ -193,4 +193,4 @@ const { handle } = tokenStore.data.tokens; | ||
const getTokenTableItemRequest: Types.TableItemRequest = { | ||
key_type: "0x1::Token::TokenId", | ||
value_type: "0x1::Token::Token", | ||
key_type: '0x1::Token::TokenId', | ||
value_type: '0x1::Token::Token', | ||
key: tokenId, | ||
@@ -197,0 +197,0 @@ }; |
// A convenience re-export from the lower level generated code | ||
import * as Types from "./api/data-contracts"; | ||
import * as Types from './api/data-contracts'; | ||
export { Types }; |
@@ -1,5 +0,5 @@ | ||
export const NODE_URL = process.env.APTOS_NODE_URL || "https://fullnode.devnet.aptoslabs.com"; | ||
export const FAUCET_URL = process.env.APTOS_FAUCET_URL || "https://faucet.devnet.aptoslabs.com"; | ||
export const NODE_URL = process.env.APTOS_NODE_URL || 'https://fullnode.devnet.aptoslabs.com'; | ||
export const FAUCET_URL = process.env.APTOS_FAUCET_URL || 'https://faucet.devnet.aptoslabs.com'; | ||
test("noop", () => { | ||
test('noop', () => { | ||
// All TS files are compiled by default into the npm package | ||
@@ -6,0 +6,0 @@ // Adding this empty test allows us to: |
{ | ||
"compilerOptions": { | ||
"experimentalDecorators": true, | ||
"outDir": "./dist", | ||
"allowJs": true, | ||
"target": "es6", | ||
"target": "es2020", | ||
"declaration": true, | ||
@@ -13,3 +14,3 @@ "declarationMap": true, | ||
"noImplicitAny": true, | ||
"allowSyntheticDefaultImports": true | ||
"allowSyntheticDefaultImports": true, | ||
}, | ||
@@ -16,0 +17,0 @@ "include": [ |
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
No v1
QualityPackage is not semver >=1. This means it is not stable and does not support ^ ranges.
Found 1 instance in 1 package
533753
218
9612
0
14