diff --git a/src/browser.ts b/src/browser.ts index 6befec18d..6af8aaf78 100644 --- a/src/browser.ts +++ b/src/browser.ts @@ -1,9 +1,9 @@ /* tslint:disable:no-var-requires */ -export * from "./index"; -export * as StellarBase from "@stellar/stellar-base"; +import axios from "axios"; -import axios from "axios"; // idk why axios is weird +export * from "./index"; +export * as StellarBase from "@stellar/stellar-base"; // idk why axios is weird export { axios }; export default module.exports; diff --git a/src/config.ts b/src/config.ts index 946c793d8..a2aa1f1b1 100644 --- a/src/config.ts +++ b/src/config.ts @@ -1,13 +1,11 @@ interface Configuration { /** * Allow connecting to http servers, default: `false`. This must be set to false in production deployments! - * * @type {boolean} */ allowHttp: boolean; /** * Allow a timeout, default: 0. Allows user to avoid nasty lag due to TOML resolve issue. You can also use {@link Config} class to set this globally. - * * @type {number} */ timeout: number; @@ -18,7 +16,7 @@ const defaultConfig: Configuration = { timeout: 0, }; -let config = Object.assign({}, defaultConfig); +let config = { ...defaultConfig}; /** * Global config class. @@ -82,7 +80,7 @@ class Config { * @returns {void} */ public static setDefault(): void { - config = Object.assign({}, defaultConfig); + config = { ...defaultConfig}; } } diff --git a/src/contract/assembled_transaction.ts b/src/contract/assembled_transaction.ts index 1f46824b9..84ea47bcd 100644 --- a/src/contract/assembled_transaction.ts +++ b/src/contract/assembled_transaction.ts @@ -388,6 +388,7 @@ export class AssembledTransaction { * ..., * simulate: false, * }) + * @param options */ static async build( options: AssembledTransactionOptions, @@ -509,6 +510,9 @@ export class AssembledTransaction { * includes the `signTransaction` method. After signing, this method will * send the transaction to the network and return a `SentTransaction` that * keeps track of all the attempts to fetch the transaction. + * @param root0 + * @param root0.force + * @param root0.signTransaction */ signAndSend = async ({ force = false, @@ -584,6 +588,8 @@ export class AssembledTransaction { * deserialize the transaction with `txFromJson`, and call * {@link AssembledTransaction#signAuthEntries}. Then re-serialize and send to * the next account in this list. + * @param root0 + * @param root0.includeAlreadySigned */ needsNonInvokerSigningBy = ({ includeAlreadySigned = false, @@ -646,6 +652,10 @@ export class AssembledTransaction { * * Sending to all `needsNonInvokerSigningBy` owners in parallel is not * currently supported! + * @param root0 + * @param root0.expiration + * @param root0.publicKey + * @param root0.signAuthEntry */ signAuthEntries = async ({ expiration = this.getStorageExpiration(), diff --git a/src/contract/basic_node_signer.ts b/src/contract/basic_node_signer.ts index 9e50327cd..0424b9bf2 100644 --- a/src/contract/basic_node_signer.ts +++ b/src/contract/basic_node_signer.ts @@ -8,6 +8,8 @@ import type { Client } from "./client"; * those classes. This is useful for testing and maybe some simple Node * applications. Feel free to use this as a starting point for your own * Wallet/TransactionSigner implementation. + * @param keypair + * @param networkPassphrase */ export const basicNodeSigner = ( /** {@link Keypair} to use to sign the transaction or auth entry */ diff --git a/src/contract/client.ts b/src/contract/client.ts index e0c298b4a..c574d5199 100644 --- a/src/contract/client.ts +++ b/src/contract/client.ts @@ -13,6 +13,8 @@ export class Client { * Each method returns an {@link AssembledTransaction} that can be used to * modify, simulate, decode results, and possibly sign, & submit the * transaction. + * @param spec + * @param options */ constructor( /** {@link Spec} to construct a Client for */ @@ -53,7 +55,6 @@ export class Client { /** * Generates a Client instance from the provided ClientOptions and the contract's wasm hash. * The wasmHash can be provided in either hex or base64 format. - * * @param wasmHash The hash of the contract's wasm binary, in either hex or base64 format. * @param options The ClientOptions object containing the necessary configuration, including the rpcUrl. * @param format The format of the provided wasmHash, either "hex" or "base64". Defaults to "hex". @@ -76,7 +77,6 @@ export class Client { /** * Generates a Client instance from the provided ClientOptions and the contract's wasm binary. - * * @param wasm The contract's wasm binary as a Buffer. * @param options The ClientOptions object containing the necessary configuration. * @returns A Promise that resolves to a Client instance. @@ -96,7 +96,6 @@ export class Client { /** * Generates a Client instance from the provided ClientOptions, which must include the contractId and rpcUrl. - * * @param options The ClientOptions object containing the necessary configuration, including the contractId and rpcUrl. * @returns A Promise that resolves to a Client instance. * @throws {TypeError} If the provided options object does not contain both rpcUrl and contractId. diff --git a/src/contract/sent_transaction.ts b/src/contract/sent_transaction.ts index d6f275d78..b6575d7d8 100644 --- a/src/contract/sent_transaction.ts +++ b/src/contract/sent_transaction.ts @@ -70,6 +70,8 @@ export class SentTransaction { * Initialize a `SentTransaction` from an existing `AssembledTransaction` and * a `signTransaction` function. This will also send the transaction to the * network. + * @param signTransaction + * @param assembled */ static init = async ( /** More info in {@link MethodOptions} */ diff --git a/src/contract/spec.ts b/src/contract/spec.ts index 937875fbb..80b141efd 100644 --- a/src/contract/spec.ts +++ b/src/contract/spec.ts @@ -14,9 +14,14 @@ export interface Union { values?: T; } +/** + * + * @param args + * @param input + */ function readObj(args: object, input: xdr.ScSpecFunctionInputV0): any { - let inputName = input.name().toString(); - let entry = Object.entries(args).find(([name, _]) => name === inputName); + const inputName = input.name().toString(); + const entry = Object.entries(args).find(([name, _]) => name === inputName); if (!entry) { throw new Error(`Missing field ${inputName}`); } @@ -26,7 +31,6 @@ function readObj(args: object, input: xdr.ScSpecFunctionInputV0): any { /** * Provides a ContractSpec class which can contains the XDR types defined by the contract. * This allows the class to be used to convert between native and raw `xdr.ScVal`s. - * * @example * ```js * const specEntries = [...]; // XDR spec entries of a smart contract @@ -53,16 +57,14 @@ export class Spec { /** * Constructs a new ContractSpec from an array of XDR spec entries. - * * @param {xdr.ScSpecEntry[] | string[]} entries the XDR spec entries - * * @throws {Error} if entries is invalid */ constructor(entries: xdr.ScSpecEntry[] | string[]) { if (entries.length == 0) { throw new Error("Contract spec must have at least one entry"); } - let entry = entries[0]; + const entry = entries[0]; if (typeof entry === "string") { this.entries = (entries as string[]).map((s) => xdr.ScSpecEntry.fromXDR(s, "base64"), @@ -74,9 +76,7 @@ export class Spec { /** * Gets the XDR functions from the spec. - * * @returns {xdr.ScSpecFunctionV0[]} all contract functions - * */ funcs(): xdr.ScSpecFunctionV0[] { return this.entries @@ -87,16 +87,15 @@ export class Spec { ) .map((entry) => entry.functionV0()); } + /** * Gets the XDR function spec for the given function name. - * * @param {string} name the name of the function * @returns {xdr.ScSpecFunctionV0} the function spec - * * @throws {Error} if no function with the given name exists */ getFunc(name: string): xdr.ScSpecFunctionV0 { - let entry = this.findEntry(name); + const entry = this.findEntry(name); if ( entry.switch().value !== xdr.ScSpecEntryKind.scSpecEntryFunctionV0().value ) { @@ -107,13 +106,10 @@ export class Spec { /** * Converts native JS arguments to ScVals for calling a contract function. - * * @param {string} name the name of the function - * @param {Object} args the arguments object + * @param {object} args the arguments object * @returns {xdr.ScVal[]} the converted arguments - * * @throws {Error} if argument is missing or incorrect type - * * @example * ```js * const args = { @@ -124,7 +120,7 @@ export class Spec { * ``` */ funcArgsToScVals(name: string, args: object): xdr.ScVal[] { - let fn = this.getFunc(name); + const fn = this.getFunc(name); return fn .inputs() .map((input) => this.nativeToScVal(readObj(args, input), input.type())); @@ -132,13 +128,10 @@ export class Spec { /** * Converts the result ScVal of a function call to a native JS value. - * * @param {string} name the name of the function * @param {xdr.ScVal | string} val_or_base64 the result ScVal or base64 encoded string * @returns {any} the converted native value - * * @throws {Error} if return type mismatch or invalid input - * * @example * ```js * const resultScv = 'AAA=='; // Base64 encoded ScVal @@ -146,14 +139,14 @@ export class Spec { * ``` */ funcResToNative(name: string, val_or_base64: xdr.ScVal | string): any { - let val = + const val = typeof val_or_base64 === "string" ? xdr.ScVal.fromXDR(val_or_base64, "base64") : val_or_base64; - let func = this.getFunc(name); - let outputs = func.outputs(); + const func = this.getFunc(name); + const outputs = func.outputs(); if (outputs.length === 0) { - let type = val.switch(); + const type = val.switch(); if (type.value !== xdr.ScValType.scvVoid().value) { throw new Error(`Expected void, got ${type.name}`); } @@ -162,7 +155,7 @@ export class Spec { if (outputs.length > 1) { throw new Error(`Multiple outputs not supported`); } - let output = outputs[0]; + const output = outputs[0]; if (output.switch().value === xdr.ScSpecType.scSpecTypeResult().value) { return new Ok(this.scValToNative(val, output.result().okType())); } @@ -171,14 +164,12 @@ export class Spec { /** * Finds the XDR spec entry for the given name. - * * @param {string} name the name to find * @returns {xdr.ScSpecEntry} the entry - * * @throws {Error} if no entry with the given name exists */ findEntry(name: string): xdr.ScSpecEntry { - let entry = this.entries.find( + const entry = this.entries.find( (entry) => entry.value().name().toString() === name, ); if (!entry) { @@ -189,22 +180,20 @@ export class Spec { /** * Converts a native JS value to an ScVal based on the given type. - * * @param {any} val the native JS value * @param {xdr.ScSpecTypeDef} [ty] the expected type * @returns {xdr.ScVal} the converted ScVal - * * @throws {Error} if value cannot be converted to the given type */ nativeToScVal(val: any, ty: xdr.ScSpecTypeDef): xdr.ScVal { - let t: xdr.ScSpecType = ty.switch(); - let value = t.value; + const t: xdr.ScSpecType = ty.switch(); + const {value} = t; if (t.value === xdr.ScSpecType.scSpecTypeUdt().value) { - let udt = ty.udt(); + const udt = ty.udt(); return this.nativeToUdt(val, udt.name().toString()); } if (value === xdr.ScSpecType.scSpecTypeOption().value) { - let opt = ty.option(); + const opt = ty.option(); if (val === undefined) { return xdr.ScVal.scvVoid(); } @@ -249,17 +238,17 @@ export class Spec { const copy = Uint8Array.from(val); switch (value) { case xdr.ScSpecType.scSpecTypeBytesN().value: { - let bytes_n = ty.bytesN(); + const bytes_n = ty.bytesN(); if (copy.length !== bytes_n.n()) { throw new TypeError( `expected ${bytes_n.n()} bytes, but got ${copy.length}`, ); } - //@ts-ignore + // @ts-ignore return xdr.ScVal.scvBytes(copy); } case xdr.ScSpecType.scSpecTypeBytes().value: - //@ts-ignore + // @ts-ignore return xdr.ScVal.scvBytes(copy); default: throw new TypeError( @@ -270,15 +259,15 @@ export class Spec { if (Array.isArray(val)) { switch (value) { case xdr.ScSpecType.scSpecTypeVec().value: { - let vec = ty.vec(); - let elementType = vec.elementType(); + const vec = ty.vec(); + const elementType = vec.elementType(); return xdr.ScVal.scvVec( val.map((v) => this.nativeToScVal(v, elementType)), ); } case xdr.ScSpecType.scSpecTypeTuple().value: { - let tup = ty.tuple(); - let valTypes = tup.valueTypes(); + const tup = ty.tuple(); + const valTypes = tup.valueTypes(); if (val.length !== valTypes.length) { throw new TypeError( `Tuple expects ${valTypes.length} values, but ${val.length} were provided`, @@ -289,13 +278,13 @@ export class Spec { ); } case xdr.ScSpecType.scSpecTypeMap().value: { - let map = ty.map(); - let keyType = map.keyType(); - let valueType = map.valueType(); + const map = ty.map(); + const keyType = map.keyType(); + const valueType = map.valueType(); return xdr.ScVal.scvMap( val.map((entry) => { - let key = this.nativeToScVal(entry[0], keyType); - let val = this.nativeToScVal(entry[1], valueType); + const key = this.nativeToScVal(entry[0], keyType); + const val = this.nativeToScVal(entry[1], valueType); return new xdr.ScMapEntry({ key, val }); }), ); @@ -311,15 +300,15 @@ export class Spec { if (value !== xdr.ScSpecType.scSpecTypeMap().value) { throw new TypeError(`Type ${ty} was not map, but value was Map`); } - let scMap = ty.map(); - let map = val as Map; - let entries: xdr.ScMapEntry[] = []; - let values = map.entries(); + const scMap = ty.map(); + const map = val as Map; + const entries: xdr.ScMapEntry[] = []; + const values = map.entries(); let res = values.next(); while (!res.done) { - let [k, v] = res.value; - let key = this.nativeToScVal(k, scMap.keyType()); - let val = this.nativeToScVal(v, scMap.valueType()); + const [k, v] = res.value; + const key = this.nativeToScVal(k, scMap.keyType()); + const val = this.nativeToScVal(v, scMap.valueType()); entries.push(new xdr.ScMapEntry({ key, val })); res = values.next(); } @@ -391,7 +380,7 @@ export class Spec { } private nativeToUdt(val: any, name: string): xdr.ScVal { - let entry = this.findEntry(name); + const entry = this.findEntry(name); switch (entry.switch()) { case xdr.ScSpecEntryKind.scSpecEntryUdtEnumV0(): if (typeof val !== "number") { @@ -413,28 +402,28 @@ export class Spec { val: Union, union_: xdr.ScSpecUdtUnionV0, ): xdr.ScVal { - let entry_name = val.tag; - let case_ = union_.cases().find((entry) => { - let case_ = entry.value().name().toString(); + const entry_name = val.tag; + const case_ = union_.cases().find((entry) => { + const case_ = entry.value().name().toString(); return case_ === entry_name; }); if (!case_) { throw new TypeError(`no such enum entry: ${entry_name} in ${union_}`); } - let key = xdr.ScVal.scvSymbol(entry_name); + const key = xdr.ScVal.scvSymbol(entry_name); switch (case_.switch()) { case xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseVoidV0(): { return xdr.ScVal.scvVec([key]); } case xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0(): { - let types = case_.tupleCase().type(); + const types = case_.tupleCase().type(); if (Array.isArray(val.values)) { if (val.values.length != types.length) { throw new TypeError( `union ${union_} expects ${types.length} values, but got ${val.values.length}`, ); } - let scvals = val.values.map((v, i) => + const scvals = val.values.map((v, i) => this.nativeToScVal(v, types[i]), ); scvals.unshift(key); @@ -448,7 +437,7 @@ export class Spec { } private nativeToStruct(val: any, struct: xdr.ScSpecUdtStructV0): xdr.ScVal { - let fields = struct.fields(); + const fields = struct.fields(); if (fields.some(isNumeric)) { if (!fields.every(isNumeric)) { throw new Error( @@ -461,7 +450,7 @@ export class Spec { } return xdr.ScVal.scvMap( fields.map((field) => { - let name = field.name().toString(); + const name = field.name().toString(); return new xdr.ScMapEntry({ key: this.nativeToScVal(name, xdr.ScSpecTypeDef.scSpecTypeSymbol()), val: this.nativeToScVal(val[name], field.type()), @@ -479,11 +468,9 @@ export class Spec { /** * Converts an base64 encoded ScVal back to a native JS value based on the given type. - * * @param {string} scv the base64 encoded ScVal * @param {xdr.ScSpecTypeDef} typeDef the expected type * @returns {any} the converted native JS value - * * @throws {Error} if ScVal cannot be converted to the given type */ scValStrToNative(scv: string, typeDef: xdr.ScSpecTypeDef): T { @@ -492,16 +479,14 @@ export class Spec { /** * Converts an ScVal back to a native JS value based on the given type. - * * @param {xdr.ScVal} scv the ScVal * @param {xdr.ScSpecTypeDef} typeDef the expected type * @returns {any} the converted native JS value - * * @throws {Error} if ScVal cannot be converted to the given type */ scValToNative(scv: xdr.ScVal, typeDef: xdr.ScSpecTypeDef): T { - let t = typeDef.switch(); - let value = t.value; + const t = typeDef.switch(); + const {value} = t; if (value === xdr.ScSpecType.scSpecTypeUdt().value) { return this.scValUdtToNative(scv, typeDef.udt()); } @@ -526,13 +511,13 @@ export class Spec { case xdr.ScValType.scvVec().value: { if (value == xdr.ScSpecType.scSpecTypeVec().value) { - let vec = typeDef.vec(); + const vec = typeDef.vec(); return (scv.vec() ?? []).map((elm) => this.scValToNative(elm, vec.elementType()), ) as T; - } else if (value == xdr.ScSpecType.scSpecTypeTuple().value) { - let tuple = typeDef.tuple(); - let valTypes = tuple.valueTypes(); + } if (value == xdr.ScSpecType.scSpecTypeTuple().value) { + const tuple = typeDef.tuple(); + const valTypes = tuple.valueTypes(); return (scv.vec() ?? []).map((elm, i) => this.scValToNative(elm, valTypes[i]), ) as T; @@ -544,12 +529,12 @@ export class Spec { return Address.fromScVal(scv).toString() as T; case xdr.ScValType.scvMap().value: { - let map = scv.map() ?? []; + const map = scv.map() ?? []; if (value == xdr.ScSpecType.scSpecTypeMap().value) { - let type_ = typeDef.map(); - let keyType = type_.keyType(); - let valueType = type_.valueType(); - let res = map.map((entry) => [ + const type_ = typeDef.map(); + const keyType = type_.keyType(); + const valueType = type_.valueType(); + const res = map.map((entry) => [ this.scValToNative(entry.key(), keyType), this.scValToNative(entry.val(), valueType), ]) as T; @@ -603,7 +588,7 @@ export class Spec { } private scValUdtToNative(scv: xdr.ScVal, udt: xdr.ScSpecTypeUdt): any { - let entry = this.findEntry(udt.name().toString()); + const entry = this.findEntry(udt.name().toString()); switch (entry.switch()) { case xdr.ScSpecEntryKind.scSpecEntryUdtEnumV0(): return this.enumToNative(scv); @@ -619,7 +604,7 @@ export class Spec { } private unionToNative(val: xdr.ScVal, udt: xdr.ScSpecUdtUnionV0): any { - let vec = val.vec(); + const vec = val.vec(); if (!vec) { throw new Error(`${JSON.stringify(val, null, 2)} is not a vec`); } @@ -628,39 +613,40 @@ export class Spec { `${val} has length 0, but the there are at least one case in the union`, ); } - let name = vec[0].sym().toString(); + const name = vec[0].sym().toString(); if (vec[0].switch().value != xdr.ScValType.scvSymbol().value) { throw new Error(`{vec[0]} is not a symbol`); } - let entry = udt.cases().find(findCase(name)); + const entry = udt.cases().find(findCase(name)); if (!entry) { throw new Error( `failed to find entry ${name} in union {udt.name().toString()}`, ); } - let res: Union = { tag: name }; + const res: Union = { tag: name }; if ( entry.switch().value === xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0().value ) { - let tuple = entry.tupleCase(); - let ty = tuple.type(); - let values = ty.map((entry, i) => this.scValToNative(vec![i + 1], entry)); + const tuple = entry.tupleCase(); + const ty = tuple.type(); + const values = ty.map((entry, i) => this.scValToNative(vec![i + 1], entry)); res.values = values; } return res; } + private structToNative(val: xdr.ScVal, udt: xdr.ScSpecUdtStructV0): any { - let res: any = {}; - let fields = udt.fields(); + const res: any = {}; + const fields = udt.fields(); if (fields.some(isNumeric)) { - let r = val + const r = val .vec() ?.map((entry, i) => this.scValToNative(entry, fields[i].type())); return r; } val.map()?.forEach((entry, i) => { - let field = fields[i]; + const field = fields[i]; res[field.name().toString()] = this.scValToNative( entry.val(), field.type(), @@ -673,15 +659,13 @@ export class Spec { if (scv.switch().value !== xdr.ScValType.scvU32().value) { throw new Error(`Enum must have a u32 value`); } - let num = scv.u32(); + const num = scv.u32(); return num; } /** * Gets the XDR error cases from the spec. - * * @returns {xdr.ScSpecFunctionV0[]} all contract functions - * */ errorCases(): xdr.ScSpecUdtErrorEnumCaseV0[] { return this.entries @@ -697,34 +681,32 @@ export class Spec { * Converts the contract spec to a JSON schema. * * If `funcName` is provided, the schema will be a reference to the function schema. - * * @param {string} [funcName] the name of the function to convert * @returns {JSONSchema7} the converted JSON schema - * * @throws {Error} if the contract spec is invalid */ jsonSchema(funcName?: string): JSONSchema7 { - let definitions: { [key: string]: JSONSchema7Definition } = {}; - for (let entry of this.entries) { + const definitions: { [key: string]: JSONSchema7Definition } = {}; + for (const entry of this.entries) { switch (entry.switch().value) { case xdr.ScSpecEntryKind.scSpecEntryUdtEnumV0().value: { - let udt = entry.udtEnumV0(); + const udt = entry.udtEnumV0(); definitions[udt.name().toString()] = enumToJsonSchema(udt); break; } case xdr.ScSpecEntryKind.scSpecEntryUdtStructV0().value: { - let udt = entry.udtStructV0(); + const udt = entry.udtStructV0(); definitions[udt.name().toString()] = structToJsonSchema(udt); break; } case xdr.ScSpecEntryKind.scSpecEntryUdtUnionV0().value: - let udt = entry.udtUnionV0(); + const udt = entry.udtUnionV0(); definitions[udt.name().toString()] = unionToJsonSchema(udt); break; case xdr.ScSpecEntryKind.scSpecEntryFunctionV0().value: { - let fn = entry.functionV0(); - let fnName = fn.name().toString(); - let { input } = functionToJsonSchema(fn); + const fn = entry.functionV0(); + const fnName = fn.name().toString(); + const { input } = functionToJsonSchema(fn); // @ts-ignore definitions[fnName] = input; break; @@ -734,17 +716,22 @@ export class Spec { } } } - let res: JSONSchema7 = { + const res: JSONSchema7 = { $schema: "http://json-schema.org/draft-07/schema#", definitions: { ...PRIMITIVE_DEFINITONS, ...definitions }, }; if (funcName) { - res["$ref"] = `#/definitions/${funcName}`; + res.$ref = `#/definitions/${funcName}`; } return res; } } +/** + * + * @param str + * @param ty + */ function stringToScVal(str: string, ty: xdr.ScSpecType): xdr.ScVal { switch (ty.value) { case xdr.ScSpecType.scSpecTypeString().value: @@ -752,7 +739,7 @@ function stringToScVal(str: string, ty: xdr.ScSpecType): xdr.ScVal { case xdr.ScSpecType.scSpecTypeSymbol().value: return xdr.ScVal.scvSymbol(str); case xdr.ScSpecType.scSpecTypeAddress().value: { - let addr = Address.fromString(str as string); + const addr = Address.fromString(str as string); return xdr.ScVal.scvAddress(addr.toScAddress()); } case xdr.ScSpecType.scSpecTypeU64().value: @@ -776,19 +763,27 @@ function stringToScVal(str: string, ty: xdr.ScSpecType): xdr.ScVal { } } +/** + * + * @param field + */ function isNumeric(field: xdr.ScSpecUdtStructFieldV0) { return /^\d+$/.test(field.name().toString()); } +/** + * + * @param name + */ function findCase(name: string) { return function matches(entry: xdr.ScSpecUdtUnionCaseV0) { switch (entry.switch().value) { case xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0().value: { - let tuple = entry.tupleCase(); + const tuple = entry.tupleCase(); return tuple.name().toString() === name; } case xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseVoidV0().value: { - let void_case = entry.voidCase(); + const void_case = entry.voidCase(); return void_case.name().toString() === name; } default: @@ -869,8 +864,8 @@ const PRIMITIVE_DEFINITONS: { [key: string]: JSONSchema7Definition } = { * @returns {JSONSchema7} a schema describing the type */ function typeRef(typeDef: xdr.ScSpecTypeDef): JSONSchema7 { - let t = typeDef.switch(); - let value = t.value; + const t = typeDef.switch(); + const {value} = t; let ref; switch (value) { case xdr.ScSpecType.scSpecTypeVal().value: { @@ -946,7 +941,7 @@ function typeRef(typeDef: xdr.ScSpecTypeDef): JSONSchema7 { break; } case xdr.ScSpecType.scSpecTypeOption().value: { - let opt = typeDef.option(); + const opt = typeDef.option(); return typeRef(opt.valueType()); } case xdr.ScSpecType.scSpecTypeResult().value: { @@ -954,16 +949,16 @@ function typeRef(typeDef: xdr.ScSpecTypeDef): JSONSchema7 { break; } case xdr.ScSpecType.scSpecTypeVec().value: { - let arr = typeDef.vec(); - let ref = typeRef(arr.elementType()); + const arr = typeDef.vec(); + const ref = typeRef(arr.elementType()); return { type: "array", items: ref, }; } case xdr.ScSpecType.scSpecTypeMap().value: { - let map = typeDef.map(); - let items = [typeRef(map.keyType()), typeRef(map.valueType())]; + const map = typeDef.map(); + const items = [typeRef(map.keyType()), typeRef(map.valueType())]; return { type: "array", items: { @@ -975,21 +970,21 @@ function typeRef(typeDef: xdr.ScSpecTypeDef): JSONSchema7 { }; } case xdr.ScSpecType.scSpecTypeTuple().value: { - let tuple = typeDef.tuple(); - let minItems = tuple.valueTypes().length; - let maxItems = minItems; - let items = tuple.valueTypes().map(typeRef); + const tuple = typeDef.tuple(); + const minItems = tuple.valueTypes().length; + const maxItems = minItems; + const items = tuple.valueTypes().map(typeRef); return { type: "array", items, minItems, maxItems }; } case xdr.ScSpecType.scSpecTypeBytesN().value: { - let arr = typeDef.bytesN(); + const arr = typeDef.bytesN(); return { $ref: "#/definitions/DataUrl", maxLength: arr.n(), }; } case xdr.ScSpecType.scSpecTypeUdt().value: { - let udt = typeDef.udt(); + const udt = typeDef.udt(); ref = udt.name().toString(); break; } @@ -999,19 +994,27 @@ function typeRef(typeDef: xdr.ScSpecTypeDef): JSONSchema7 { type Func = { input: JSONSchema7; output: JSONSchema7 }; +/** + * + * @param typeDef + */ function isRequired(typeDef: xdr.ScSpecTypeDef): boolean { return typeDef.switch().value != xdr.ScSpecType.scSpecTypeOption().value; } +/** + * + * @param udt + */ function structToJsonSchema(udt: xdr.ScSpecUdtStructV0): object { - let fields = udt.fields(); + const fields = udt.fields(); if (fields.some(isNumeric)) { if (!fields.every(isNumeric)) { throw new Error( "mixed numeric and non-numeric field names are not allowed", ); } - let items = fields.map((_, i) => typeRef(fields[i].type())); + const items = fields.map((_, i) => typeRef(fields[i].type())); return { type: "array", items, @@ -1019,9 +1022,9 @@ function structToJsonSchema(udt: xdr.ScSpecUdtStructV0): object { maxItems: fields.length, }; } - let description = udt.doc().toString(); - let { properties, required }: any = args_and_required(fields); - properties["additionalProperties"] = false; + const description = udt.doc().toString(); + const { properties, required }: any = args_and_required(fields); + properties.additionalProperties = false; return { description, properties, @@ -1030,29 +1033,37 @@ function structToJsonSchema(udt: xdr.ScSpecUdtStructV0): object { }; } +/** + * + * @param input + */ function args_and_required( input: { type: () => xdr.ScSpecTypeDef; name: () => string | Buffer }[], ): { properties: object; required?: string[] } { - let properties: any = {}; - let required: string[] = []; - for (let arg of input) { - let type_ = arg.type(); - let name = arg.name().toString(); + const properties: any = {}; + const required: string[] = []; + for (const arg of input) { + const type_ = arg.type(); + const name = arg.name().toString(); properties[name] = typeRef(type_); if (isRequired(type_)) { required.push(name); } } - let res: { properties: object; required?: string[] } = { properties }; + const res: { properties: object; required?: string[] } = { properties }; if (required.length > 0) { res.required = required; } return res; } +/** + * + * @param func + */ function functionToJsonSchema(func: xdr.ScSpecFunctionV0): Func { - let { properties, required }: any = args_and_required(func.inputs()); - let args: any = { + const { properties, required }: any = args_and_required(func.inputs()); + const args: any = { additionalProperties: false, properties, type: "object", @@ -1060,17 +1071,17 @@ function functionToJsonSchema(func: xdr.ScSpecFunctionV0): Func { if (required?.length > 0) { args.required = required; } - let input: Partial = { + const input: Partial = { properties: { args, }, }; - let outputs = func.outputs(); - let output: Partial = + const outputs = func.outputs(); + const output: Partial = outputs.length > 0 ? typeRef(outputs[0]) : typeRef(xdr.ScSpecTypeDef.scSpecTypeVoid()); - let description = func.doc().toString(); + const description = func.doc().toString(); if (description.length > 0) { input.description = description; } @@ -1082,15 +1093,19 @@ function functionToJsonSchema(func: xdr.ScSpecFunctionV0): Func { }; } +/** + * + * @param udt + */ function unionToJsonSchema(udt: xdr.ScSpecUdtUnionV0): any { - let description = udt.doc().toString(); - let cases = udt.cases(); - let oneOf: any[] = []; - for (let case_ of cases) { + const description = udt.doc().toString(); + const cases = udt.cases(); + const oneOf: any[] = []; + for (const case_ of cases) { switch (case_.switch().value) { case xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseVoidV0().value: { - let c = case_.voidCase(); - let title = c.name().toString(); + const c = case_.voidCase(); + const title = c.name().toString(); oneOf.push({ type: "object", title, @@ -1103,8 +1118,8 @@ function unionToJsonSchema(udt: xdr.ScSpecUdtUnionV0): any { break; } case xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0().value: { - let c = case_.tupleCase(); - let title = c.name().toString(); + const c = case_.tupleCase(); + const title = c.name().toString(); oneOf.push({ type: "object", title, @@ -1122,7 +1137,7 @@ function unionToJsonSchema(udt: xdr.ScSpecUdtUnionV0): any { } } - let res: any = { + const res: any = { oneOf, }; if (description.length > 0) { @@ -1131,13 +1146,17 @@ function unionToJsonSchema(udt: xdr.ScSpecUdtUnionV0): any { return res; } +/** + * + * @param udt + */ function enumToJsonSchema(udt: xdr.ScSpecUdtEnumV0): any { - let description = udt.doc().toString(); - let cases = udt.cases(); - let oneOf: any[] = []; - for (let case_ of cases) { - let title = case_.name().toString(); - let description = case_.doc().toString(); + const description = udt.doc().toString(); + const cases = udt.cases(); + const oneOf: any[] = []; + for (const case_ of cases) { + const title = case_.name().toString(); + const description = case_.doc().toString(); oneOf.push({ description, title, @@ -1146,7 +1165,7 @@ function enumToJsonSchema(udt: xdr.ScSpecUdtEnumV0): any { }); } - let res: any = { oneOf }; + const res: any = { oneOf }; if (description.length > 0) { res.description = description; } diff --git a/src/contract/utils.ts b/src/contract/utils.ts index 44e7b8b02..f8db49621 100644 --- a/src/contract/utils.ts +++ b/src/contract/utils.ts @@ -9,6 +9,11 @@ export const DEFAULT_TIMEOUT = 5 * 60; /** * Keep calling a `fn` for `timeoutInSeconds` seconds, if `keepWaitingIf` is * true. Returns an array of all attempts to call the function. + * @param fn + * @param keepWaitingIf + * @param timeoutInSeconds + * @param exponentialFactor + * @param verbose */ export async function withExponentialBackoff( /** Function to call repeatedly */ @@ -87,6 +92,7 @@ export const contractErrorPattern = /Error\(Contract, #(\d+)\)/; /** * A TypeScript type guard that checks if an object has a `toString` method. + * @param obj */ export function implementsToString( /** some object that may or may not have a `toString` method */ @@ -97,6 +103,7 @@ export function implementsToString( /** * Reads a binary stream of ScSpecEntries into an array for processing by ContractSpec + * @param buffer */ export function processSpecEntryStream(buffer: Buffer) { const reader = new cereal.XdrReader(buffer); diff --git a/src/errors.ts b/src/errors.ts index b84f72162..38a70e85e 100644 --- a/src/errors.ts +++ b/src/errors.ts @@ -10,6 +10,7 @@ export class NetworkError extends Error { statusText?: string; url?: string; }; + public __proto__: NetworkError; constructor(message: string, response: any) { @@ -72,10 +73,12 @@ export class BadResponseError extends NetworkError { */ export class AccountRequiresMemoError extends Error { public __proto__: AccountRequiresMemoError; + /** * accountId account which requires a memo. */ public accountId: string; + /** * operationIndex operation where accountId is the destination. */ diff --git a/src/federation/server.ts b/src/federation/server.ts index 06d88fc87..53bc02c8c 100644 --- a/src/federation/server.ts +++ b/src/federation/server.ts @@ -15,7 +15,7 @@ export const FEDERATION_RESPONSE_MAX_SIZE = 100 * 1024; * FederationServer handles a network connection to a * [federation server](https://developers.stellar.org/docs/glossary/federation/) * instance and exposes an interface for requests to that instance. - * @constructor + * @class * @param {string} serverURL The federation server URL (ex. `https://acme.com/federation`). * @param {string} domain Domain this server represents * @param {object} [opts] options object @@ -26,20 +26,19 @@ export const FEDERATION_RESPONSE_MAX_SIZE = 100 * 1024; export class FederationServer { /** * The federation server URL (ex. `https://acme.com/federation`). - * * @memberof FederationServer */ private readonly serverURL: URI; // TODO: public or private? readonly? + /** * Domain this server represents. - * * @type {string} * @memberof FederationServer */ private readonly domain: string; // TODO: public or private? readonly? + /** * Allow a timeout, default: 0. Allows user to avoid nasty lag due to TOML resolve issue. - * * @type {number} * @memberof FederationServer */ @@ -49,25 +48,24 @@ export class FederationServer { * A helper method for handling user inputs that contain `destination` value. * It accepts two types of values: * - * * For Stellar address (ex. `bob*stellar.org`) it splits Stellar address and then tries to find information about + * For Stellar address (ex. `bob*stellar.org`) it splits Stellar address and then tries to find information about * federation server in `stellar.toml` file for a given domain. It returns a `Promise` which resolves if federation * server exists and user has been found and rejects in all other cases. - * * For Account ID (ex. `GB5XVAABEQMY63WTHDQ5RXADGYF345VWMNPTN2GFUDZT57D57ZQTJ7PS`) it returns a `Promise` which + * For Account ID (ex. `GB5XVAABEQMY63WTHDQ5RXADGYF345VWMNPTN2GFUDZT57D57ZQTJ7PS`) it returns a `Promise` which * resolves if Account ID is valid and rejects in all other cases. Please note that this method does not check * if the account actually exists in a ledger. * * Example: * ```js * StellarSdk.FederationServer.resolve('bob*stellar.org') - * .then(federationRecord => { - * // { - * // account_id: 'GB5XVAABEQMY63WTHDQ5RXADGYF345VWMNPTN2GFUDZT57D57ZQTJ7PS', - * // memo_type: 'id', - * // memo: 100 - * // } - * }); + * .then(federationRecord => { + * // { + * // account_id: 'GB5XVAABEQMY63WTHDQ5RXADGYF345VWMNPTN2GFUDZT57D57ZQTJ7PS', + * // memo_type: 'id', + * // memo: 100 + * // } + * }); * ``` - * * @see Federation doc * @see Stellar.toml doc * @param {string} value Stellar Address (ex. `bob*stellar.org`) @@ -75,9 +73,9 @@ export class FederationServer { * @param {boolean} [opts.allowHttp] - Allow connecting to http servers, default: `false`. This must be set to false in production deployments! * @param {number} [opts.timeout] - Allow a timeout, default: 0. Allows user to avoid nasty lag due to TOML resolve issue. * @returns {Promise} `Promise` that resolves to a JSON object with this shape: - * * `account_id` - Account ID of the destination, - * * `memo_type` (optional) - Memo type that needs to be attached to a transaction, - * * `memo` (optional) - Memo value that needs to be attached to a transaction. + * `account_id` - Account ID of the destination, + * `memo_type` (optional) - Memo type that needs to be attached to a transaction, + * `memo` (optional) - Memo value that needs to be attached to a transaction. */ public static async resolve( value: string, @@ -213,7 +211,7 @@ export class FederationServer { } private async _sendRequest(url: URI) { - const timeout = this.timeout; + const {timeout} = this; return axios .get(url.toString(), { diff --git a/src/horizon/account_call_builder.ts b/src/horizon/account_call_builder.ts index 06997053a..dc02ad2a8 100644 --- a/src/horizon/account_call_builder.ts +++ b/src/horizon/account_call_builder.ts @@ -5,11 +5,10 @@ import { ServerApi } from "./server_api"; /** * Creates a new {@link AccountCallBuilder} pointed to server defined by serverUrl. * Do not create this object directly, use {@link Server#accounts}. - * * @see [All Accounts](https://developers.stellar.org/api/resources/accounts/) * @class AccountCallBuilder - * @extends CallBuilder - * @constructor + * @augments CallBuilder + * @class * @param {string} serverUrl Horizon server URL. */ export class AccountCallBuilder extends CallBuilder< @@ -23,7 +22,6 @@ export class AccountCallBuilder extends CallBuilder< /** * Returns information and links relating to a single account. * The balances section in the returned JSON will also list all the trust lines this account has set up. - * * @see [Account Details](https://developers.stellar.org/api/resources/accounts/single/) * @param {string} id For example: `GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDD` * @returns {CallBuilder} a new CallBuilder instance for the /accounts/:id endpoint @@ -70,7 +68,6 @@ export class AccountCallBuilder extends CallBuilder< /** * This endpoint filters accounts holding a trustline to the given liquidity pool. - * * @param {string} id The ID of the liquidity pool. For example: `dd7b1ab831c273310ddbec6f97870aa83c2fbd78ce22aded37ecbf4f3380fac7`. * @returns {AccountCallBuilder} current AccountCallBuilder instance */ diff --git a/src/horizon/account_response.ts b/src/horizon/account_response.ts index 376e9a197..65016737f 100644 --- a/src/horizon/account_response.ts +++ b/src/horizon/account_response.ts @@ -10,46 +10,67 @@ import { ServerApi } from "./server_api"; * Returns information and links relating to a single account. * The balances section in the returned JSON will also list all the trust lines this account has set up. * It also contains {@link Account} object and exposes it's methods so can be used in {@link TransactionBuilder}. - * * @see [Account Details](https://developers.stellar.org/api/resources/accounts/object/) * @param {string} response Response from horizon account endpoint. * @returns {AccountResponse} AccountResponse instance */ export class AccountResponse { public readonly id!: string; + public readonly paging_token!: string; + public readonly account_id!: string; + public sequence!: string; + public readonly sequence_ledger?: number; + public readonly sequence_time?: string; + public readonly subentry_count!: number; + public readonly home_domain?: string; + public readonly inflation_destination?: string; + public readonly last_modified_ledger!: number; + public readonly last_modified_time!: string; + public readonly thresholds!: HorizonApi.AccountThresholds; + public readonly flags!: HorizonApi.Flags; + public readonly balances!: HorizonApi.BalanceLine[]; + public readonly signers!: ServerApi.AccountRecordSigners[]; + public readonly data!: (options: { value: string; }) => Promise<{ value: string }>; + public readonly data_attr!: Record; + public readonly effects!: ServerApi.CallCollectionFunction< ServerApi.EffectRecord >; + public readonly offers!: ServerApi.CallCollectionFunction< ServerApi.OfferRecord >; + public readonly operations!: ServerApi.CallCollectionFunction< ServerApi.OperationRecord >; + public readonly payments!: ServerApi.CallCollectionFunction< ServerApi.PaymentOperationRecord >; + public readonly trades!: ServerApi.CallCollectionFunction< ServerApi.TradeRecord >; + private readonly _baseAccount: BaseAccount; constructor(response: ServerApi.AccountRecord) { diff --git a/src/horizon/assets_call_builder.ts b/src/horizon/assets_call_builder.ts index 29d63200a..591bf7a37 100644 --- a/src/horizon/assets_call_builder.ts +++ b/src/horizon/assets_call_builder.ts @@ -6,8 +6,8 @@ import { ServerApi } from "./server_api"; * * Do not create this object directly, use {@link Server#assets}. * @class AssetsCallBuilder - * @constructor - * @extends CallBuilder + * @class + * @augments CallBuilder * @param {string} serverUrl Horizon server URL. */ export class AssetsCallBuilder extends CallBuilder< diff --git a/src/horizon/call_builder.ts b/src/horizon/call_builder.ts index d8c6f8ec4..010648436 100644 --- a/src/horizon/call_builder.ts +++ b/src/horizon/call_builder.ts @@ -20,7 +20,7 @@ export interface EventSourceOptions { const anyGlobal = global as any; type Constructable = new (e: string) => T; // require("eventsource") for Node and React Native environment -let EventSource: Constructable = anyGlobal.EventSource ?? +const EventSource: Constructable = anyGlobal.EventSource ?? anyGlobal.window?.EventSource ?? require("eventsource"); @@ -38,8 +38,11 @@ export class CallBuilder< | ServerApi.CollectionPage > { protected url: URI; + public filter: string[][]; + protected originalSegments: string[]; + protected neighborRoot: string; constructor(serverUrl: URI, neighborRoot: string = "") { @@ -59,22 +62,22 @@ export class CallBuilder< this._parseResponse(r), ); } - //// TODO: Migrate to async, BUT that's a change in behavior and tests "rejects two filters" will fail. - //// It's because async will check within promise, which makes more sense when using awaits instead of Promises. + /// / TODO: Migrate to async, BUT that's a change in behavior and tests "rejects two filters" will fail. + /// / It's because async will check within promise, which makes more sense when using awaits instead of Promises. // public async call(): Promise { // this.checkFilter(); // const r = await this._sendNormalRequest(this.url); // return this._parseResponse(r); // } - //// /* actually equals */ - //// public call(): Promise { - //// return Promise.resolve().then(() => { - //// this.checkFilter(); - //// return this._sendNormalRequest(this.url) - //// }).then((r) => { - //// this._parseResponse(r) - //// }); - //// } + /// / /* actually equals */ + /// / public call(): Promise { + /// / return Promise.resolve().then(() => { + /// / this.checkFilter(); + /// / return this._sendNormalRequest(this.url) + /// / }).then((r) => { + /// / this._parseResponse(r) + /// / }); + /// / } /** * Creates an EventSource that listens for incoming messages from the server. To stop listening for new @@ -82,10 +85,10 @@ export class CallBuilder< * @see [Horizon Response Format](https://developers.stellar.org/api/introduction/response-format/) * @see [MDN EventSource](https://developer.mozilla.org/en-US/docs/Web/API/EventSource) * @param {object} [options] EventSource options. - * @param {function} [options.onmessage] Callback function to handle incoming messages. - * @param {function} [options.onerror] Callback function to handle errors. + * @param {Function} [options.onmessage] Callback function to handle incoming messages. + * @param {Function} [options.onerror] Callback function to handle errors. * @param {number} [options.reconnectTimeout] Custom stream connection timeout in ms, default is 15 seconds. - * @returns {function} Close function. Run to close the connection and stop listening for new events. + * @returns {Function} Close function. Run to close the connection and stop listening for new events. */ public stream(options: EventSourceOptions = {}): () => void { this.checkFilter(); @@ -195,6 +198,7 @@ export class CallBuilder< /** * Sets `limit` parameter for the current call. Returns the CallBuilder object on which this method has been called. * @see [Paging](https://developers.stellar.org/api/introduction/pagination/) + * @param recordsNumber * @param {number} number Number of records the server should return. * @returns {object} current CallBuilder instance */ @@ -220,8 +224,8 @@ export class CallBuilder< * supported on the operations and payments endpoints. The response * will include a `transaction` field for each operation in the * response. - * * @param {"transactions"} join Records to be included in the response. + * @param include * @returns {object} current CallBuilder instance. */ public join(include: "transactions"): this { @@ -232,16 +236,14 @@ export class CallBuilder< /** * A helper method to craft queries to "neighbor" endpoints. * - * For example, we have an `/effects` suffix endpoint on many different - * "root" endpoints, such as `/transactions/:id` and `/accounts/:id`. So, - * it's helpful to be able to conveniently create queries to the - * `/accounts/:id/effects` endpoint: - * - * this.forEndpoint("accounts", accountId)`. + * For example, we have an `/effects` suffix endpoint on many different + * "root" endpoints, such as `/transactions/:id` and `/accounts/:id`. So, + * it's helpful to be able to conveniently create queries to the + * `/accounts/:id/effects` endpoint: * + * this.forEndpoint("accounts", accountId)`. * @param {string} endpoint neighbor endpoint in question, like /operations * @param {string} param filter parameter, like an operation ID - * * @returns {CallBuilder} this CallBuilder instance */ protected forEndpoint(endpoint: string, param: string): this { @@ -274,7 +276,7 @@ export class CallBuilder< * @param {object} link A link object * @param {bool} link.href the URI of the link * @param {bool} [link.templated] Whether the link is templated - * @returns {function} A function that requests the link + * @returns {Function} A function that requests the link */ private _requestFnForLink(link: HorizonApi.ResponseLink): (opts?: any) => any { return async (opts: any = {}) => { diff --git a/src/horizon/claimable_balances_call_builder.ts b/src/horizon/claimable_balances_call_builder.ts index bf515702a..ae98c6f40 100644 --- a/src/horizon/claimable_balances_call_builder.ts +++ b/src/horizon/claimable_balances_call_builder.ts @@ -5,11 +5,10 @@ import { ServerApi } from "./server_api"; /** * Creates a new {@link ClaimableBalanceCallBuilder} pointed to server defined by serverUrl. * Do not create this object directly, use {@link Server#claimableBalances}. - * * @see [Claimable Balances](https://developers.stellar.org/api/resources/claimablebalances/) * @class ClaimableBalanceCallBuilder - * @constructor - * @extends CallBuilder + * @class + * @augments CallBuilder * @param {string} serverUrl Horizon server URL. */ export class ClaimableBalanceCallBuilder extends CallBuilder< @@ -22,7 +21,6 @@ export class ClaimableBalanceCallBuilder extends CallBuilder< /** * The claimable balance details endpoint provides information on a single claimable balance. - * * @see [Claimable Balance Details](https://developers.stellar.org/api/resources/claimablebalances/single/) * @param {string} claimableBalanceId Claimable balance ID * @returns {CallBuilder} CallBuilder OperationCallBuilder instance @@ -39,7 +37,6 @@ export class ClaimableBalanceCallBuilder extends CallBuilder< /** * Returns all claimable balances which are sponsored by the given account ID. - * * @see [Claimable Balances](https://developers.stellar.org/api/resources/claimablebalances/list/) * @param {string} sponsor For example: `GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDD` * @returns {ClaimableBalanceCallBuilder} current ClaimableBalanceCallBuilder instance @@ -51,7 +48,6 @@ export class ClaimableBalanceCallBuilder extends CallBuilder< /** * Returns all claimable balances which can be claimed by the given account ID. - * * @see [Claimable Balances](https://developers.stellar.org/api/resources/claimablebalances/list/) * @param {string} claimant For example: `GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDD` * @returns {ClaimableBalanceCallBuilder} current ClaimableBalanceCallBuilder instance @@ -63,8 +59,8 @@ export class ClaimableBalanceCallBuilder extends CallBuilder< /** * Returns all claimable balances which provide a balance for the given asset. - * * @see [Claimable Balances](https://developers.stellar.org/api/resources/claimablebalances/list/) + * @param asset * @param {Asset} The Asset held by the claimable balance * @returns {ClaimableBalanceCallBuilder} current ClaimableBalanceCallBuilder instance */ diff --git a/src/horizon/effect_call_builder.ts b/src/horizon/effect_call_builder.ts index d6db8cc28..f6347de76 100644 --- a/src/horizon/effect_call_builder.ts +++ b/src/horizon/effect_call_builder.ts @@ -4,11 +4,10 @@ import { ServerApi } from "./server_api"; /** * Creates a new {@link EffectCallBuilder} pointed to server defined by serverUrl. * Do not create this object directly, use {@link Server#effects}. - * * @class EffectCallBuilder - * @extends CallBuilder + * @augments CallBuilder * @see [All Effects](https://developers.stellar.org/api/resources/effects/) - * @constructor + * @class * @param {string} serverUrl Horizon server URL. */ export class EffectCallBuilder extends CallBuilder< @@ -63,7 +62,6 @@ export class EffectCallBuilder extends CallBuilder< /** * This endpoint represents all effects involving a particular liquidity pool. - * * @param {string} poolId liquidity pool ID * @returns {EffectCallBuilder} this EffectCallBuilder instance */ diff --git a/src/horizon/horizon_axios_client.ts b/src/horizon/horizon_axios_client.ts index a76da401f..154681f8f 100644 --- a/src/horizon/horizon_axios_client.ts +++ b/src/horizon/horizon_axios_client.ts @@ -2,7 +2,7 @@ import axios, { AxiosResponse } from "axios"; import URI from "urijs"; /* tslint:disable-next-line:no-var-requires */ -export const version = require("../../package.json").version; +export const {version} = require("../../package.json"); export interface ServerTime { serverTime: number; @@ -30,12 +30,16 @@ export const AxiosClient = axios.create({ }, }); +/** + * + * @param ms + */ function _toSeconds(ms: number): number { return Math.floor(ms / 1000); } AxiosClient.interceptors.response.use( - function interceptorHorizonResponse(response: AxiosResponse) { + (response: AxiosResponse) => { const hostname = URI(response.config.url!).hostname(); const serverTime = _toSeconds(Date.parse(response.headers.date)); const localTimeRecorded = _toSeconds(new Date().getTime()); diff --git a/src/horizon/ledger_call_builder.ts b/src/horizon/ledger_call_builder.ts index 5e74a85b5..8708940d9 100644 --- a/src/horizon/ledger_call_builder.ts +++ b/src/horizon/ledger_call_builder.ts @@ -4,11 +4,10 @@ import { ServerApi } from "./server_api"; /** * Creates a new {@link LedgerCallBuilder} pointed to server defined by serverUrl. * Do not create this object directly, use {@link Server#ledgers}. - * * @see [All Ledgers](https://developers.stellar.org/api/resources/ledgers/list/) - * @constructor + * @class * @class LedgerCallBuilder - * @extends CallBuilder + * @augments CallBuilder * @param {string} serverUrl Horizon server URL. */ export class LedgerCallBuilder extends CallBuilder< diff --git a/src/horizon/liquidity_pool_call_builder.ts b/src/horizon/liquidity_pool_call_builder.ts index f6c24b1f5..0657fd62f 100644 --- a/src/horizon/liquidity_pool_call_builder.ts +++ b/src/horizon/liquidity_pool_call_builder.ts @@ -6,10 +6,9 @@ import { ServerApi } from "./server_api"; /** * Creates a new {@link LiquidityPoolCallBuilder} pointed to server defined by serverUrl. * Do not create this object directly, use {@link Server#liquidityPools}. - * * @class LiquidityPoolCallBuilder - * @extends CallBuilder - * @constructor + * @augments CallBuilder + * @class * @param {string} serverUrl Horizon server URL. */ export class LiquidityPoolCallBuilder extends CallBuilder< @@ -22,7 +21,6 @@ export class LiquidityPoolCallBuilder extends CallBuilder< /** * Filters out pools whose reserves don't exactly match these assets. - * * @see Asset * @param {Asset[]} assets * @returns {LiquidityPoolCallBuilder} current LiquidityPoolCallBuilder instance @@ -37,7 +35,6 @@ export class LiquidityPoolCallBuilder extends CallBuilder< /** * Retrieves all pools an account is participating in. - * * @param {string} id the participant account to filter by * @returns {LiquidityPoolCallBuilder} current LiquidityPoolCallBuilder instance */ @@ -48,7 +45,6 @@ export class LiquidityPoolCallBuilder extends CallBuilder< /** * Retrieves a specific liquidity pool by ID. - * * @param {string} id the hash/ID of the liquidity pool * @returns {CallBuilder} a new CallBuilder instance for the /liquidity_pools/:id endpoint */ diff --git a/src/horizon/offer_call_builder.ts b/src/horizon/offer_call_builder.ts index 4d40b1a4b..15b76a8a7 100644 --- a/src/horizon/offer_call_builder.ts +++ b/src/horizon/offer_call_builder.ts @@ -5,11 +5,10 @@ import { ServerApi } from "./server_api"; /** * Creates a new {@link OfferCallBuilder} pointed to server defined by serverUrl. * Do not create this object directly, use {@link Server#offers}. - * * @see [Offers](https://developers.stellar.org/api/resources/offers/) * @class OfferCallBuilder - * @constructor - * @extends CallBuilder + * @class + * @augments CallBuilder * @param {string} serverUrl Horizon server URL. */ export class OfferCallBuilder extends CallBuilder< @@ -35,7 +34,6 @@ export class OfferCallBuilder extends CallBuilder< /** * Returns all offers where the given account is involved. - * * @see [Offers](https://developers.stellar.org/api/resources/accounts/offers/) * @param {string} id For example: `GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDD` * @returns {OfferCallBuilder} current OfferCallBuilder instance @@ -93,7 +91,6 @@ export class OfferCallBuilder extends CallBuilder< /** * This endpoint filters offers where the given account is the seller. - * * @see [Offers](https://developers.stellar.org/api/resources/offers/list/) * @param {string} seller For example: `GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDD` * @returns {OfferCallBuilder} current OfferCallBuilder instance diff --git a/src/horizon/operation_call_builder.ts b/src/horizon/operation_call_builder.ts index e7573e7ba..e9a7dd3a4 100644 --- a/src/horizon/operation_call_builder.ts +++ b/src/horizon/operation_call_builder.ts @@ -4,11 +4,10 @@ import { ServerApi } from "./server_api"; /** * Creates a new {@link OperationCallBuilder} pointed to server defined by serverUrl. * Do not create this object directly, use {@link Server#operations}. - * * @see [All Operations](https://developers.stellar.org/api/resources/operations/) * @class OperationCallBuilder - * @constructor - * @extends CallBuilder + * @class + * @augments CallBuilder * @param {string} serverUrl Horizon server URL. */ export class OperationCallBuilder extends CallBuilder< @@ -58,7 +57,6 @@ export class OperationCallBuilder extends CallBuilder< /** * This endpoint returns all operations that occurred in a given ledger. - * * @see [Operations for Ledger](https://developers.stellar.org/api/resources/ledgers/operations/) * @param {number|string} sequence Ledger sequence * @returns {OperationCallBuilder} this OperationCallBuilder instance @@ -79,7 +77,6 @@ export class OperationCallBuilder extends CallBuilder< /** * This endpoint represents all operations involving a particular liquidity pool. - * * @param {string} poolId liquidity pool ID * @returns {OperationCallBuilder} this OperationCallBuilder instance */ @@ -89,8 +86,7 @@ export class OperationCallBuilder extends CallBuilder< /** * Adds a parameter defining whether to include failed transactions. - * By default, only operations of successful transactions are returned. - * + * By default, only operations of successful transactions are returned. * @param {bool} value Set to `true` to include operations of failed transactions. * @returns {OperationCallBuilder} this OperationCallBuilder instance */ diff --git a/src/horizon/path_call_builder.ts b/src/horizon/path_call_builder.ts index 4999e07d8..80108ac81 100644 --- a/src/horizon/path_call_builder.ts +++ b/src/horizon/path_call_builder.ts @@ -9,9 +9,9 @@ import { ServerApi } from "./server_api"; * * A path search is specified using: * - * * The destination address - * * The source address - * * The asset and amount that the destination account should receive + * The destination address + * The source address + * The asset and amount that the destination account should receive * * As part of the search, horizon will load a list of assets available to the source address and will find any * payment paths from those source assets to the desired destination asset. The search's amount parameter will be @@ -19,7 +19,7 @@ import { ServerApi } from "./server_api"; * * Do not create this object directly, use {@link Server#paths}. * @see [Find Payment Paths](https://developers.stellar.org/api/aggregations/paths/) - * @extends CallBuilder + * @augments CallBuilder * @param {string} serverUrl Horizon server URL. * @param {string} source The sender's account ID. Any returned path must use a source that the sender can hold. * @param {string} destination The destination account ID that any returned path should use. diff --git a/src/horizon/payment_call_builder.ts b/src/horizon/payment_call_builder.ts index 82e103fb1..1e5c8cb6b 100644 --- a/src/horizon/payment_call_builder.ts +++ b/src/horizon/payment_call_builder.ts @@ -6,8 +6,8 @@ import { ServerApi } from "./server_api"; * * Do not create this object directly, use {@link Server#payments}. * @see [All Payments](https://developers.stellar.org/api/horizon/resources/list-all-payments/) - * @constructor - * @extends CallBuilder + * @class + * @augments CallBuilder * @param {string} serverUrl Horizon server URL. */ export class PaymentCallBuilder extends CallBuilder< diff --git a/src/horizon/server.ts b/src/horizon/server.ts index 48c92106d..3e29a1b7c 100644 --- a/src/horizon/server.ts +++ b/src/horizon/server.ts @@ -50,6 +50,10 @@ const STROOPS_IN_LUMEN = 10000000; // SEP 29 uses this value to define transaction memo requirements for incoming payments. const ACCOUNT_REQUIRES_MEMO = "MQ=="; +/** + * + * @param amt + */ function _getAmountInLumens(amt: BigNumber) { return new BigNumber(amt).div(STROOPS_IN_LUMEN).toString(); } @@ -57,7 +61,7 @@ function _getAmountInLumens(amt: BigNumber) { /** * Server handles the network connection to a [Horizon](https://developers.stellar.org/api/introduction/) * instance and exposes an interface for requests to that instance. - * @constructor + * @class * @param {string} serverURL Horizon Server URL (ex. `https://horizon-testnet.stellar.org`). * @param {object} [opts] Options object * @param {boolean} [opts.allowHttp] - Allow connecting to http servers, default: `false`. This must be set to false in production deployments! You can also use {@link Config} class to set this globally. @@ -131,8 +135,10 @@ export class Server { * // earlier does the trick! * .build(); * ``` - * @argument {number} seconds Number of seconds past the current time to wait. - * @argument {bool} [_isRetry=false] True if this is a retry. Only set this internally! + * @param seconds + * @param {number} seconds Number of seconds past the current time to wait. + * @param _isRetry + * @param {bool} [_isRetry] True if this is a retry. Only set this internally! * This is to avoid a scenario where Horizon is horking up the wrong date. * @returns {Promise} Promise that resolves a `timebounds` object * (with the shape `{ minTime: 0, maxTime: N }`) that you can set the `timebounds` option to. @@ -162,7 +168,7 @@ export class Server { // otherwise, retry (by calling the root endpoint) // toString automatically adds the trailing slash await AxiosClient.get(URI(this.serverURL as any).toString()); - return await this.fetchTimebounds(seconds, true); + return this.fetchTimebounds(seconds, true); } /** @@ -203,87 +209,86 @@ export class Server { * Ex: * ```javascript * const res = { - * ...response, - * offerResults: [ - * { - * // Exact ordered list of offers that executed, with the exception - * // that the last one may not have executed entirely. - * offersClaimed: [ - * sellerId: String, - * offerId: String, - * assetSold: { - * type: 'native|credit_alphanum4|credit_alphanum12', - * - * // these are only present if the asset is not native - * assetCode: String, - * issuer: String, - * }, - * - * // same shape as assetSold - * assetBought: {} - * ], - * - * // What effect your manageOffer op had - * effect: "manageOfferCreated|manageOfferUpdated|manageOfferDeleted", - * - * // Whether your offer immediately got matched and filled - * wasImmediatelyFilled: Boolean, - * - * // Whether your offer immediately got deleted, if for example the order was too small - * wasImmediatelyDeleted: Boolean, - * - * // Whether the offer was partially, but not completely, filled - * wasPartiallyFilled: Boolean, - * - * // The full requested amount of the offer is open for matching - * isFullyOpen: Boolean, - * - * // The total amount of tokens bought / sold during transaction execution - * amountBought: Number, - * amountSold: Number, - * - * // if the offer was created, updated, or partially filled, this is - * // the outstanding offer - * currentOffer: { - * offerId: String, - * amount: String, - * price: { - * n: String, - * d: String, - * }, - * - * selling: { - * type: 'native|credit_alphanum4|credit_alphanum12', - * - * // these are only present if the asset is not native - * assetCode: String, - * issuer: String, - * }, - * - * // same as `selling` - * buying: {}, - * }, - * - * // the index of this particular operation in the op stack - * operationIndex: Number - * } - * ] + * ...response, + * offerResults: [ + * { + * // Exact ordered list of offers that executed, with the exception + * // that the last one may not have executed entirely. + * offersClaimed: [ + * sellerId: String, + * offerId: String, + * assetSold: { + * type: 'native|credit_alphanum4|credit_alphanum12', + * + * // these are only present if the asset is not native + * assetCode: String, + * issuer: String, + * }, + * + * // same shape as assetSold + * assetBought: {} + * ], + * + * // What effect your manageOffer op had + * effect: "manageOfferCreated|manageOfferUpdated|manageOfferDeleted", + * + * // Whether your offer immediately got matched and filled + * wasImmediatelyFilled: Boolean, + * + * // Whether your offer immediately got deleted, if for example the order was too small + * wasImmediatelyDeleted: Boolean, + * + * // Whether the offer was partially, but not completely, filled + * wasPartiallyFilled: Boolean, + * + * // The full requested amount of the offer is open for matching + * isFullyOpen: Boolean, + * + * // The total amount of tokens bought / sold during transaction execution + * amountBought: Number, + * amountSold: Number, + * + * // if the offer was created, updated, or partially filled, this is + * // the outstanding offer + * currentOffer: { + * offerId: String, + * amount: String, + * price: { + * n: String, + * d: String, + * }, + * + * selling: { + * type: 'native|credit_alphanum4|credit_alphanum12', + * + * // these are only present if the asset is not native + * assetCode: String, + * issuer: String, + * }, + * + * // same as `selling` + * buying: {}, + * }, + * + * // the index of this particular operation in the op stack + * operationIndex: Number + * } + * ] * } * ``` * * For example, you'll want to examine `offerResults` to add affordances like * these to your app: - * * If `wasImmediatelyFilled` is true, then no offer was created. So if you - * normally watch the `Server.offers` endpoint for offer updates, you - * instead need to check `Server.trades` to find the result of this filled - * offer. - * * If `wasImmediatelyDeleted` is true, then the offer you submitted was - * deleted without reaching the orderbook or being matched (possibly because - * your amounts were rounded down to zero). So treat the just-submitted - * offer request as if it never happened. - * * If `wasPartiallyFilled` is true, you can tell the user that - * `amountBought` or `amountSold` have already been transferred. - * + * If `wasImmediatelyFilled` is true, then no offer was created. So if you + * normally watch the `Server.offers` endpoint for offer updates, you + * instead need to check `Server.trades` to find the result of this filled + * offer. + * If `wasImmediatelyDeleted` is true, then the offer you submitted was + * deleted without reaching the orderbook or being matched (possibly because + * your amounts were rounded down to zero). So treat the just-submitted + * offer request as if it never happened. + * If `wasPartiallyFilled` is true, you can tell the user that + * `amountBought` or `amountSold` have already been transferred. * @see [Post * Transaction](https://developers.stellar.org/api/resources/transactions/post/) * @param {Transaction|FeeBumpTransaction} transaction - The transaction to submit. @@ -377,8 +382,8 @@ export class Server { // However, you can never be too careful. default: throw new Error( - "Invalid offer result type: " + - offerClaimedAtom.switch(), + `Invalid offer result type: ${ + offerClaimedAtom.switch()}`, ); } @@ -488,9 +493,7 @@ export class Server { .filter((result: any) => !!result); } - return Object.assign({}, response.data, { - offerResults: hasManageOffer ? offerResults : undefined, - }); + return { ...response.data, offerResults: hasManageOffer ? offerResults : undefined,}; }) .catch((response) => { if (response instanceof Error) { @@ -595,9 +598,9 @@ export class Server { * * A strict receive path search is specified using: * - * * The destination address. - * * The source address or source assets. - * * The asset and amount that the destination account should receive. + * The destination address. + * The source address or source assets. + * The asset and amount that the destination account should receive. * * As part of the search, horizon will load a list of assets available to the * source address and will find any payment paths from those source assets to @@ -607,7 +610,6 @@ export class Server { * * If a list of assets is passed as the source, horizon will find any payment * paths from those source assets to the desired destination asset. - * * @param {string|Asset[]} source The sender's account ID or a list of assets. Any returned path will use a source that the sender can hold. * @param {Asset} destinationAsset The destination asset. * @param {string} destinationAmount The amount, denominated in the destination asset, that any returned path should be able to satisfy. @@ -635,7 +637,6 @@ export class Server { * * The asset and amount that is being sent. * The destination account or the destination assets. - * * @param {Asset} sourceAsset The asset to be sent. * @param {string} sourceAmount The amount, denominated in the source asset, that any returned path should be able to satisfy. * @param {string|Asset[]} destination The destination account or the destination assets. @@ -692,9 +693,7 @@ export class Server { /** * Fetches an account's most current state in the ledger, then creates and * returns an {@link AccountResponse} object. - * * @param {string} accountId - The account to load. - * * @returns {Promise} Returns a promise to the {@link AccountResponse} object * with populated sequence number. */ @@ -746,7 +745,6 @@ export class Server { * * Each account is checked sequentially instead of loading multiple accounts * at the same time from Horizon. - * * @see https://stellar.org/protocol/sep-29 * @param {Transaction} transaction - The transaction to check. * @returns {Promise} - If any of the destination account @@ -778,7 +776,7 @@ export class Server { default: continue; } - const destination = operation.destination; + const {destination} = operation; if (destinations.has(destination)) { continue; } diff --git a/src/horizon/server_api.ts b/src/horizon/server_api.ts index 049f98b04..b567498e7 100644 --- a/src/horizon/server_api.ts +++ b/src/horizon/server_api.ts @@ -182,6 +182,7 @@ export namespace ServerApi { import OperationResponseType = HorizonApi.OperationResponseType; import OperationResponseTypeI = HorizonApi.OperationResponseTypeI; + export interface BaseOperationRecord< T extends OperationResponseType = OperationResponseType, TI extends OperationResponseTypeI = OperationResponseTypeI diff --git a/src/horizon/strict_receive_path_call_builder.ts b/src/horizon/strict_receive_path_call_builder.ts index b44876780..f8857e05a 100644 --- a/src/horizon/strict_receive_path_call_builder.ts +++ b/src/horizon/strict_receive_path_call_builder.ts @@ -10,8 +10,8 @@ import { ServerApi } from "./server_api"; * * A path search is specified using: * - * * The source address or source assets. - * * The asset and amount that the destination account should receive + * The source address or source assets. + * The asset and amount that the destination account should receive * * As part of the search, horizon will load a list of assets available to the * source address and will find any payment paths from those source assets to @@ -23,7 +23,7 @@ import { ServerApi } from "./server_api"; * * Do not create this object directly, use {@link Server#strictReceivePaths}. * @see [Find Payment Paths](https://developers.stellar.org/api/aggregations/paths/) - * @extends CallBuilder + * @augments CallBuilder * @param {string} serverUrl Horizon server URL. * @param {string|Asset[]} source The sender's account ID or a list of Assets. Any returned path must use a source that the sender can hold. * @param {Asset} destinationAsset The destination asset. diff --git a/src/horizon/strict_send_path_call_builder.ts b/src/horizon/strict_send_path_call_builder.ts index da840374b..674bcd867 100644 --- a/src/horizon/strict_send_path_call_builder.ts +++ b/src/horizon/strict_send_path_call_builder.ts @@ -22,12 +22,11 @@ import { ServerApi } from "./server_api"; * * Do not create this object directly, use {@link Server#strictSendPaths}. * @see [Find Payment Paths](https://developers.stellar.org/api/aggregations/paths/) - * @extends CallBuilder + * @augments CallBuilder * @param {string} serverUrl Horizon server URL. * @param {Asset} sourceAsset The asset to be sent. * @param {string} sourceAmount The amount, denominated in the source asset, that any returned path should be able to satisfy. * @param {string|Asset[]} destination The destination account or the destination assets. - * */ export class StrictSendPathCallBuilder extends CallBuilder< ServerApi.CollectionPage diff --git a/src/horizon/trade_aggregation_call_builder.ts b/src/horizon/trade_aggregation_call_builder.ts index 8dfff4f69..695f364a7 100644 --- a/src/horizon/trade_aggregation_call_builder.ts +++ b/src/horizon/trade_aggregation_call_builder.ts @@ -17,10 +17,9 @@ const allowedResolutions = [ /** * Trade Aggregations facilitate efficient gathering of historical trade data. * Do not create this object directly, use {@link Server#tradeAggregation}. - * * @class TradeAggregationCallBuilder - * @extends CallBuilder - * @constructor + * @augments CallBuilder + * @class * @param {string} serverUrl serverUrl Horizon server URL. * @param {Asset} base base asset * @param {Asset} counter counter asset diff --git a/src/horizon/trades_call_builder.ts b/src/horizon/trades_call_builder.ts index 8c601454d..daf229aa8 100644 --- a/src/horizon/trades_call_builder.ts +++ b/src/horizon/trades_call_builder.ts @@ -5,10 +5,9 @@ import { ServerApi } from "./server_api"; /** * Creates a new {@link TradesCallBuilder} pointed to server defined by serverUrl. * Do not create this object directly, use {@link Server#trades}. - * * @class TradesCallBuilder - * @extends CallBuilder - * @constructor + * @augments CallBuilder + * @class * @see [Trades](https://developers.stellar.org/api/resources/trades/) * @param {string} serverUrl serverUrl Horizon server URL. */ diff --git a/src/horizon/transaction_call_builder.ts b/src/horizon/transaction_call_builder.ts index 831c4ee6f..4d7583925 100644 --- a/src/horizon/transaction_call_builder.ts +++ b/src/horizon/transaction_call_builder.ts @@ -4,11 +4,10 @@ import { ServerApi } from "./server_api"; /** * Creates a new {@link TransactionCallBuilder} pointed to server defined by serverUrl. * Do not create this object directly, use {@link Server#transactions}. - * * @class TransactionCallBuilder - * @extends CallBuilder + * @augments CallBuilder * @see [All Transactions](https://developers.stellar.org/api/resources/transactions/) - * @constructor + * @class * @param {string} serverUrl Horizon server URL. */ export class TransactionCallBuilder extends CallBuilder< @@ -67,7 +66,6 @@ export class TransactionCallBuilder extends CallBuilder< /** * This endpoint represents all transactions involving a particular liquidity pool. - * * @param {string} poolId liquidity pool ID * @returns {TransactionCallBuilder} this TransactionCallBuilder instance */ diff --git a/src/horizon/types/assets.ts b/src/horizon/types/assets.ts index 76708718c..844e76d63 100644 --- a/src/horizon/types/assets.ts +++ b/src/horizon/types/assets.ts @@ -1,5 +1,5 @@ import { AssetType } from "@stellar/stellar-base"; -import { HorizonApi } from "./../horizon_api"; +import { HorizonApi } from "../horizon_api"; export interface AssetRecord extends HorizonApi.BaseResponse { asset_type: AssetType.credit4 | AssetType.credit12; diff --git a/src/horizon/types/effects.ts b/src/horizon/types/effects.ts index 7742295d8..f7d0c8af7 100644 --- a/src/horizon/types/effects.ts +++ b/src/horizon/types/effects.ts @@ -1,4 +1,4 @@ -import { HorizonApi } from "./../horizon_api"; +import { HorizonApi } from "../horizon_api"; import { OfferAsset } from "./offer"; // Reference: GO SDK https://github.com/stellar/go/blob/ec5600bd6b2b6900d26988ff670b9ca7992313b8/services/horizon/internal/resourceadapter/effects.go diff --git a/src/horizon/types/offer.ts b/src/horizon/types/offer.ts index 9a0de5000..7331664bb 100644 --- a/src/horizon/types/offer.ts +++ b/src/horizon/types/offer.ts @@ -1,5 +1,5 @@ import { AssetType } from "@stellar/stellar-base"; -import { HorizonApi } from "./../horizon_api"; +import { HorizonApi } from "../horizon_api"; export interface OfferAsset { asset_type: AssetType; diff --git a/src/rpc/api.ts b/src/rpc/api.ts index 3c8d7806f..bd2bd4ad9 100644 --- a/src/rpc/api.ts +++ b/src/rpc/api.ts @@ -33,7 +33,8 @@ export namespace Api { key: string; /** a base-64 encoded {@link xdr.LedgerEntryData} instance */ xdr: string; - /** optional, a future ledger number upon which this entry will expire + /** + * optional, a future ledger number upon which this entry will expire * based on https://github.com/stellar/soroban-tools/issues/1010 */ liveUntilLedgerSeq?: number; @@ -222,13 +223,12 @@ export namespace Api { /** * Simplifies {@link RawSimulateTransactionResponse} into separate interfaces * based on status: - * - on success, this includes all fields, though `result` is only present - * if an invocation was simulated (since otherwise there's nothing to - * "resultify") - * - if there was an expiration error, this includes error and restoration - * fields - * - for all other errors, this only includes error fields - * + * - on success, this includes all fields, though `result` is only present + * if an invocation was simulated (since otherwise there's nothing to + * "resultify") + * - if there was an expiration error, this includes error and restoration + * fields + * - for all other errors, this only includes error fields * @see https://soroban.stellar.org/api/methods/simulateTransaction#returns */ export type SimulateTransactionResponse = @@ -291,18 +291,30 @@ export namespace Api { }; } + /** + * + * @param sim + */ export function isSimulationError( sim: SimulateTransactionResponse ): sim is SimulateTransactionErrorResponse { return 'error' in sim; } + /** + * + * @param sim + */ export function isSimulationSuccess( sim: SimulateTransactionResponse ): sim is SimulateTransactionSuccessResponse { return 'transactionData' in sim; } + /** + * + * @param sim + */ export function isSimulationRestore( sim: SimulateTransactionResponse ): sim is SimulateTransactionRestoreResponse { @@ -313,6 +325,10 @@ export namespace Api { ); } + /** + * + * @param sim + */ export function isSimulationRaw( sim: | Api.SimulateTransactionResponse diff --git a/src/rpc/axios.ts b/src/rpc/axios.ts index bf19ff7d9..ba154a315 100644 --- a/src/rpc/axios.ts +++ b/src/rpc/axios.ts @@ -1,7 +1,8 @@ import axios from 'axios'; /* tslint:disable-next-line:no-var-requires */ -export const version = require('../../package.json').version; +export const {version} = require('../../package.json'); + export const AxiosClient = axios.create({ headers: { 'X-Client-Name': 'js-soroban-client', diff --git a/src/rpc/browser.ts b/src/rpc/browser.ts index a5ce47b04..d08334f21 100644 --- a/src/rpc/browser.ts +++ b/src/rpc/browser.ts @@ -1,9 +1,9 @@ /* tslint:disable:no-var-requires */ -export * from './index'; -export * as StellarBase from '@stellar/stellar-base'; +import axios from 'axios'; -import axios from 'axios'; // idk why axios is weird +export * from './index'; +export * as StellarBase from '@stellar/stellar-base'; // idk why axios is weird export { axios }; export default module.exports; diff --git a/src/rpc/jsonrpc.ts b/src/rpc/jsonrpc.ts index bd93ebbef..388af1628 100644 --- a/src/rpc/jsonrpc.ts +++ b/src/rpc/jsonrpc.ts @@ -26,7 +26,12 @@ export interface Error { data?: E; } -/** Sends the jsonrpc 'params' as a single 'param' object (no array support). */ +/** + * Sends the jsonrpc 'params' as a single 'param' object (no array support). + * @param url + * @param method + * @param param + */ export async function postObject( url: string, method: string, @@ -48,6 +53,11 @@ export async function postObject( // Check if the given object X has a field Y, and make that available to // typescript typing. +/** + * + * @param obj + * @param prop + */ function hasOwnProperty( obj: X, prop: Y, diff --git a/src/rpc/parsers.ts b/src/rpc/parsers.ts index 8ff1d1c6d..9dc1ae561 100644 --- a/src/rpc/parsers.ts +++ b/src/rpc/parsers.ts @@ -1,6 +1,10 @@ import { xdr, Contract, SorobanDataBuilder } from '@stellar/stellar-base'; import { Api } from './api'; +/** + * + * @param r + */ export function parseRawSendTransaction( r: Api.RawSendTransactionResponse ): Api.SendTransactionResponse { @@ -8,7 +12,7 @@ export function parseRawSendTransaction( delete r.errorResultXdr; delete r.diagnosticEventsXdr; - if (!!errorResultXdr) { + if (errorResultXdr) { return { ...r, ...( @@ -26,6 +30,10 @@ export function parseRawSendTransaction( return { ...r } as Api.BaseSendTransactionResponse; } +/** + * + * @param r + */ export function parseRawEvents( r: Api.RawGetEventsResponse ): Api.GetEventsResponse { @@ -46,6 +54,10 @@ export function parseRawEvents( }; } +/** + * + * @param raw + */ export function parseRawLedgerEntries( raw: Api.RawGetLedgerEntriesResponse ): Api.GetLedgerEntriesResponse { @@ -73,12 +85,10 @@ export function parseRawLedgerEntries( /** * Converts a raw response schema into one with parsed XDR fields and a * simplified interface. - * * @param raw the raw response schema (parsed ones are allowed, best-effort * detected, and returned untouched) - * + * @param sim * @returns the original parameter (if already parsed), parsed otherwise - * * @warning This API is only exported for testing purposes and should not be * relied on or considered "stable". */ @@ -94,7 +104,7 @@ export function parseRawSimulation( } // shared across all responses - let base: Api.BaseSimulateTransactionResponse = { + const base: Api.BaseSimulateTransactionResponse = { _parsed: true, id: sim.id, latestLedger: sim.latestLedger, @@ -113,6 +123,11 @@ export function parseRawSimulation( return parseSuccessful(sim, base); } +/** + * + * @param sim + * @param partial + */ function parseSuccessful( sim: Api.RawSimulateTransactionResponse, partial: Api.BaseSimulateTransactionResponse @@ -128,17 +143,15 @@ function parseSuccessful( ...// coalesce 0-or-1-element results[] list into a single result struct // with decoded fields if present ((sim.results?.length ?? 0 > 0) && { - result: sim.results!.map((row) => { - return { + result: sim.results!.map((row) => ({ auth: (row.auth ?? []).map((entry) => xdr.SorobanAuthorizationEntry.fromXDR(entry, 'base64') ), // if return value is missing ("falsy") we coalesce to void - retval: !!row.xdr + retval: row.xdr ? xdr.ScVal.fromXDR(row.xdr, 'base64') : xdr.ScVal.scvVoid() - }; - })[0] + }))[0] }) }; diff --git a/src/rpc/server.ts b/src/rpc/server.ts index e3c518efb..ae38be7d4 100644 --- a/src/rpc/server.ts +++ b/src/rpc/server.ts @@ -55,9 +55,7 @@ export namespace Server { /** * Handles the network connection to a Soroban RPC instance, exposing an * interface for requests to that instance. - * - * @constructor - * + * @class * @param {string} serverURL Soroban-RPC Server URL (ex. * `http://localhost:8000/soroban/rpc`). * @param {object} [opts] Options object @@ -65,7 +63,6 @@ export namespace Server { * (default: `false`). This must be set to false in production deployments! * You can also use {@link Config} class to set this globally. * @param {Record} [opts.headers] allows setting custom headers - * * @see https://soroban.stellar.org/api/methods */ export class Server { @@ -95,12 +92,9 @@ export class Server { * * Needed to get the current sequence number for the account so you can build * a successful transaction with {@link TransactionBuilder}. - * * @param {string} address - The public address of the account to load. - * * @returns {Promise} a promise to the {@link Account} object with * a populated sequence number - * * @see https://soroban.stellar.org/api/methods/getLedgerEntries * @example * const accountId = "GBZC6Y2Y7Q3ZQ2Y4QZJ2XZ3Z5YXZ6Z7Z2Y4QZJ2XZ3Z5YXZ6Z7Z2Y4"; @@ -129,11 +123,9 @@ export class Server { /** * General node health check. - * * @returns {Promise} a promise to the * {@link Api.GetHealthResponse} object with the status of the * server (e.g. "healthy"). - * * @see https://soroban.stellar.org/api/methods/getHealth * @example * server.getHealth().then((health) => { @@ -153,20 +145,16 @@ export class Server { * Allows you to directly inspect the current state of a contract. This is a * backup way to access your contract data which may not be available via * events or {@link Server.simulateTransaction}. - * * @param {string|Address|Contract} contract the contract ID containing the * data to load as a strkey (`C...` form), a {@link Contract}, or an * {@link Address} instance * @param {xdr.ScVal} key the key of the contract data to load - * @param {Durability} [durability=Durability.Persistent] the "durability + * @param {Durability} [durability] the "durability * keyspace" that this ledger key belongs to, which is either 'temporary' * or 'persistent' (the default), see {@link Durability}. - * * @returns {Promise} the current data value - * * @warning If the data entry in question is a 'temporary' entry, it's * entirely possible that it has expired out of existence. - * * @see https://soroban.stellar.org/api/methods/getLedgerEntries * @example * const contractId = "CCJZ5DGASBWQXR5MPFCJXMBI333XE5U3FSJTNQU7RIKE3P5GN2K2WYD5"; @@ -209,7 +197,7 @@ export class Server { throw new TypeError(`invalid durability: ${durability}`); } - let contractKey = xdr.LedgerKey.contractData( + const contractKey = xdr.LedgerKey.contractData( new xdr.LedgerKeyContractData({ key, contract: scAddress, @@ -241,15 +229,11 @@ export class Server { * This method allows you to fetch the WASM bytecode associated with a contract * deployed on the Soroban network. The WASM bytecode represents the executable * code of the contract. - * * @param {string} contractId the contract ID containing the * WASM bytecode to retrieve - * * @returns {Promise} a Buffer containing the WASM bytecode - * * @throws {Error} If the contract or its associated WASM bytecode cannot be * found on the network. - * * @example * const contractId = "CCJZ5DGASBWQXR5MPFCJXMBI333XE5U3FSJTNQU7RIKE3P5GN2K2WYD5"; * server.getContractWasmByContractId(contractId).then(wasmBuffer => { @@ -284,14 +268,11 @@ export class Server { * This method allows you to fetch the WASM bytecode associated with a contract * deployed on the Soroban network using the contract's WASM hash. The WASM bytecode * represents the executable code of the contract. - * * @param {Buffer} wasmHash the WASM hash of the contract - * + * @param format * @returns {Promise} a Buffer containing the WASM bytecode - * * @throws {Error} If the contract or its associated WASM bytecode cannot be * found on the network. - * * @example * const wasmHash = Buffer.from("..."); * server.getContractWasmByHash(wasmHash).then(wasmBuffer => { @@ -331,12 +312,9 @@ export class Server { * To fetch a contract's WASM byte-code, built the appropriate * {@link xdr.LedgerKeyContractCode} ledger entry key (or see * {@link Contract.getFootprint}). - * * @param {xdr.ScVal[]} keys one or more ledger entry keys to load - * * @returns {Promise} the current * on-chain values for the given ledger keys - * * @see Server._getLedgerEntries * @see https://soroban.stellar.org/api/methods/getLedgerEntries * @example @@ -376,12 +354,9 @@ export class Server { * * After submitting a transaction, clients should poll this to tell when the * transaction has completed. - * * @param {string} hash hex-encoded hash of the transaction to check - * * @returns {Promise} the status, * result, and other details about the transaction - * * @see https://soroban.stellar.org/api/methods/getTransaction * @example * const transactionHash = "c4515e3bdc0897f21cc5dbec8c82cf0a936d4741cb74a8e158eb51b9fb00411a"; @@ -450,11 +425,9 @@ export class Server { * * To page through events, use the `pagingToken` field on the relevant * {@link Api.EventResponse} object to set the `cursor` parameter. - * * @param {Server.GetEventsRequest} request event filters * @returns {Promise} a paginatable set of the * events matching the given event filters - * * @see https://soroban.stellar.org/api/methods/getEvents * @example * server.getEvents({ @@ -502,10 +475,8 @@ export class Server { /** * Fetch metadata about the network this Soroban RPC server is connected to. - * * @returns {Promise} metadata about the * current network this RPC server is connected to - * * @see https://soroban.stellar.org/api/methods/getNetwork * @example * server.getNetwork().then((network) => { @@ -515,16 +486,14 @@ export class Server { * }); */ public async getNetwork(): Promise { - return await jsonrpc.postObject(this.serverURL.toString(), 'getNetwork'); + return jsonrpc.postObject(this.serverURL.toString(), 'getNetwork'); } /** * Fetch the latest ledger meta info from network which this Soroban RPC * server is connected to. - * * @returns {Promise} metadata about the * latest ledger on the network that this RPC server is connected to - * * @see https://soroban.stellar.org/api/methods/getLatestLedger * @example * server.getLatestLedger().then((response) => { @@ -540,22 +509,20 @@ export class Server { /** * Submit a trial contract invocation to get back return values, expected * ledger footprint, expected authorizations, and expected costs. - * * @param {Transaction | FeeBumpTransaction} transaction the transaction to * simulate, which should include exactly one operation (one of * {@link xdr.InvokeHostFunctionOp}, {@link xdr.ExtendFootprintTTLOp}, or * {@link xdr.RestoreFootprintOp}). Any provided footprint or auth * information will be ignored. - * + * @param tx + * @param addlResources * @returns {Promise} an object with the * cost, footprint, result/auth requirements (if applicable), and error of * the transaction - * * @see https://developers.stellar.org/docs/glossary/transactions/ * @see https://soroban.stellar.org/api/methods/simulateTransaction * @see Server.prepareTransaction * @see assembleTransaction - * * @example * const contractId = 'CA3D5KRYM6CB7OWQ6TWYRR3Z4T7GNZLKERYNZGGA5SOAOPIFY6YQGAXE'; * const contract = new StellarSdk.Contract(contractId); @@ -621,7 +588,6 @@ export class Server { * You can call the {@link Server.simulateTransaction} method directly first * if you want to inspect estimated fees for a given transaction in detail * first, then re-assemble it manually or via {@link assembleTransaction}. - * * @param {Transaction | FeeBumpTransaction} transaction the transaction to * prepare. It should include exactly one operation, which must be one of * {@link xdr.InvokeHostFunctionOp}, {@link xdr.ExtendFootprintTTLOp}, @@ -632,13 +598,12 @@ export class Server { * from the simulation. In other words, if you include auth entries, you * don't care about the auth returned from the simulation. Other fields * (footprint, etc.) will be filled as normal. - * + * @param tx * @returns {Promise} a copy of the * transaction with the expected authorizations (in the case of * invocation), resources, and ledger footprints added. The transaction fee * will also automatically be padded with the contract's minimum resource * fees discovered from the simulation. - * * @see assembleTransaction * @see https://soroban.stellar.org/api/methods/simulateTransaction * @throws {jsonrpc.Error|Error|Api.SimulateTransactionErrorResponse} @@ -690,11 +655,9 @@ export class Server { * simply validates the transaction and enqueues it. Clients should call * {@link Server.getTransactionStatus} to learn about transaction * success/failure. - * * @param {Transaction | FeeBumpTransaction} transaction to submit * @returns {Promise} the * transaction id, status, and any error if available - * * @see https://developers.stellar.org/docs/glossary/transactions/ * @see https://soroban.stellar.org/api/methods/sendTransaction * @example @@ -744,21 +707,17 @@ export class Server { /** * Fund a new account using the network's friendbot faucet, if any. - * * @param {string | Account} address the address or account instance that we * want to create and fund with friendbot * @param {string} [friendbotUrl] optionally, an explicit address for * friendbot (by default: this calls the Soroban RPC * {@link Server.getNetwork} method to try to discover this network's * Friendbot url). - * * @returns {Promise} an {@link Account} object for the created * account, or the existing account if it's already funded with the * populated sequence number (note that the account will not be "topped * off" if it already exists) - * * @throws if Friendbot is not configured on this network or request failure - * * @see * https://developers.stellar.org/docs/fundamentals-and-concepts/testnet-and-pubnet#friendbot * @see Friendbot.Response @@ -804,6 +763,10 @@ export class Server { } } +/** + * + * @param meta + */ function findCreatedAccountSequenceInTransactionMeta( meta: xdr.TransactionMeta ): string { diff --git a/src/rpc/transaction.ts b/src/rpc/transaction.ts index c75f333b4..95180266b 100644 --- a/src/rpc/transaction.ts +++ b/src/rpc/transaction.ts @@ -10,18 +10,14 @@ import { parseRawSimulation } from './parsers'; /** * Combines the given raw transaction alongside the simulation results. - * * @param raw the initial transaction, w/o simulation applied * @param simulation the Soroban RPC simulation result (see * {@link Server.simulateTransaction}) - * * @returns a new, cloned transaction with the proper auth and resource (fee, * footprint) simulation data applied - * * @note if the given transaction already has authorization entries in a host * function invocation (see {@link Operation.invokeHostFunction}), **the * simulation entries are ignored**. - * * @see {Server.simulateTransaction} * @see {Server.prepareTransaction} */ @@ -47,7 +43,7 @@ export function assembleTransaction( ); } - let success = parseRawSimulation(simulation); + const success = parseRawSimulation(simulation); if (!Api.isSimulationSuccess(success)) { throw new Error(`simulation incorrect: ${JSON.stringify(success)}`); } @@ -94,6 +90,10 @@ export function assembleTransaction( return txnBuilder; } +/** + * + * @param tx + */ function isSorobanTransaction(tx: Transaction): boolean { if (tx.operations.length !== 1) { return false; diff --git a/src/rpc/utils.ts b/src/rpc/utils.ts index af4bb76a2..578b6dd87 100644 --- a/src/rpc/utils.ts +++ b/src/rpc/utils.ts @@ -1,5 +1,10 @@ // Check if the given object X has a field Y, and make that available to // typescript typing. +/** + * + * @param obj + * @param prop + */ export function hasOwnProperty( obj: X, prop: Y, diff --git a/src/stellartoml/index.ts b/src/stellartoml/index.ts index ba0c965bf..efeb6fd33 100644 --- a/src/stellartoml/index.ts +++ b/src/stellartoml/index.ts @@ -9,7 +9,7 @@ export const STELLAR_TOML_MAX_SIZE = 100 * 1024; // axios timeout doesn't catch missing urls, e.g. those with no response // so we use the axios cancel token to ensure the timeout -const CancelToken = axios.CancelToken; +const {CancelToken} = axios; /** Resolver allows resolving `stellar.toml` files. */ export class Resolver { diff --git a/src/utils.ts b/src/utils.ts index 3186a51ff..fbf64c0a8 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -3,8 +3,8 @@ import { Transaction } from "@stellar/stellar-base"; export class Utils { /** * Verifies if the current date is within the transaction's timebonds - * * @static + * @param gracePeriod * @function * @param {Transaction} transaction the transaction whose timebonds will be validated. * @returns {boolean} returns true if the current time is within the transaction's [minTime, maxTime] range. diff --git a/src/webauth/utils.ts b/src/webauth/utils.ts index 3e6d13c73..3adbcd6bf 100644 --- a/src/webauth/utils.ts +++ b/src/webauth/utils.ts @@ -20,16 +20,14 @@ import { ServerApi } from "../horizon/server_api"; /** * Returns a valid [SEP-10](https://stellar.org/protocol/sep-10) challenge * transaction which you can use for Stellar Web Authentication. - * * @function * @memberof WebAuth - * * @param {Keypair} serverKeypair Keypair for server's signing account. * @param {string} clientAccountID The stellar account (G...) or muxed account * (M...) that the wallet wishes to authenticate with the server. * @param {string} homeDomain The fully qualified domain name of the service * requiring authentication - * @param {number} [timeout=300] Challenge duration (default to 5 minutes). + * @param {number} [timeout] Challenge duration (default to 5 minutes). * @param {string} networkPassphrase The network passphrase. If you pass this * argument then timeout is required. * @param {string} webAuthDomain The fully qualified domain name of the service @@ -43,11 +41,9 @@ import { ServerApi } from "../horizon/server_api"; * @param {string} [clientSigningKey] The public key assigned to the SIGNING_KEY * attribute specified on the stellar.toml hosted on the client domain. Only * necessary when the 'client_domain' parameter is passed. - * * @returns {string} A base64 encoded string of the raw TransactionEnvelope xdr * struct for the transaction. * @see [SEP-10: Stellar Web Auth](https://stellar.org/protocol/sep-10). - * * @example * import { Keypair, Networks, WebAuth } from 'stellar-sdk' * @@ -144,10 +140,8 @@ export function buildChallengeTx( * of the following functions to completely verify the transaction: * - {@link verifyChallengeTxThreshold} * - {@link verifyChallengeTxSigners} - * * @function * @memberof WebAuth - * * @param {string} challengeTx SEP0010 challenge transaction in base64. * @param {string} serverAccountID The server's stellar account (public key). * @param {string} networkPassphrase The network passphrase, e.g.: 'Test SDF @@ -158,12 +152,10 @@ export function buildChallengeTx( * @param {string} webAuthDomain The home domain that is expected to be included * as the value of the Manage Data operation with the 'web_auth_domain' key. * If no such operation is included, this parameter is not used. - * * @returns {Transaction|string|string|string} The actual transaction and the * stellar public key (master key) used to sign the Manage Data operation, * the matched home domain, and the memo attached to the transaction, which * will be null if not present. - * * @see [SEP-10: Stellar Web Auth](https://stellar.org/protocol/sep-10). */ export function readChallengeTx( @@ -362,15 +354,13 @@ export function readChallengeTx( * ignored. * * Errors will be raised if: - * - The transaction is invalid according to {@link readChallengeTx}. - * - No client signatures are found on the transaction. - * - One or more signatures in the transaction are not identifiable as the - * server account or one of the signers provided in the arguments. - * - The signatures are all valid but do not meet the threshold. - * + * - The transaction is invalid according to {@link readChallengeTx}. + * - No client signatures are found on the transaction. + * - One or more signatures in the transaction are not identifiable as the + * server account or one of the signers provided in the arguments. + * - The signatures are all valid but do not meet the threshold. * @function * @memberof WebAuth - * * @param {string} challengeTx SEP0010 challenge transaction in base64. * @param {string} serverAccountID The server's stellar account (public key). * @param {string} networkPassphrase The network passphrase, e.g.: 'Test SDF @@ -386,11 +376,9 @@ export function readChallengeTx( * @param {string} webAuthDomain The home domain that is expected to be included * as the value of the Manage Data operation with the 'web_auth_domain' key, * if present. Used in verifyChallengeTxSigners() => readChallengeTx(). - * * @returns {string[]} The list of signers public keys that have signed the * transaction, excluding the server account ID, given that the threshold was * met. - * * @see [SEP-10: Stellar Web Auth](https://stellar.org/protocol/sep-10). * @example * import { Networks, TransactionBuilder, WebAuth } from 'stellar-sdk'; @@ -490,14 +478,12 @@ export function verifyChallengeTxThreshold( * ignored. * * Errors will be raised if: - * - The transaction is invalid according to {@link readChallengeTx}. - * - No client signatures are found on the transaction. - * - One or more signatures in the transaction are not identifiable as the - * server account or one of the signers provided in the arguments. - * + * - The transaction is invalid according to {@link readChallengeTx}. + * - No client signatures are found on the transaction. + * - One or more signatures in the transaction are not identifiable as the + * server account or one of the signers provided in the arguments. * @function * @memberof WebAuth - * * @param {string} challengeTx SEP0010 challenge transaction in base64. * @param {string} serverAccountID The server's stellar account (public key). * @param {string} networkPassphrase The network passphrase, e.g.: 'Test SDF @@ -512,7 +498,6 @@ export function verifyChallengeTxThreshold( * if present. Used in readChallengeTx(). * @returns {string[]} The list of signers public keys that have signed the * transaction, excluding the server account ID. - * * @see [SEP-10: Stellar Web Auth](https://stellar.org/protocol/sep-10). * @example * import { Networks, TransactionBuilder, WebAuth } from 'stellar-sdk'; @@ -572,8 +557,8 @@ export function verifyChallengeTxSigners( serverKP = Keypair.fromPublicKey(serverAccountID); // can throw 'Invalid Stellar public key' } catch (err: any) { throw new Error( - "Couldn't infer keypair from the provided 'serverAccountID': " + - err.message, + `Couldn't infer keypair from the provided 'serverAccountID': ${ + err.message}`, ); } @@ -645,7 +630,7 @@ export function verifyChallengeTxSigners( // Confirm we matched a signature to the server signer. if (!serverSignatureFound) { throw new InvalidChallengeError( - "Transaction not signed by server: '" + serverKP.publicKey() + "'", + `Transaction not signed by server: '${ serverKP.publicKey() }'`, ); } @@ -683,13 +668,11 @@ export function verifyChallengeTxSigners( /** * Verifies if a transaction was signed by the given account id. - * * @function * @memberof WebAuth * @param {Transaction} transaction * @param {string} accountID * @returns {boolean}. - * * @example * let keypair = Keypair.random(); * const account = new StellarSdk.Account(keypair.publicKey(), "-1"); @@ -712,14 +695,12 @@ export function verifyTxSignedBy( * Checks if a transaction has been signed by one or more of the given signers, * returning a list of non-repeated signers that were found to have signed the * given transaction. - * * @function * @memberof WebAuth * @param {Transaction} transaction the signed transaction. * @param {string[]} signers The signers public keys. * @returns {string[]} a list of signers that were found to have signed the * transaction. - * * @example * let keypair1 = Keypair.random(); * let keypair2 = Keypair.random(); @@ -751,7 +732,7 @@ export function gatherTxSigners( keypair = Keypair.fromPublicKey(signer); // This can throw a few different errors } catch (err: any) { throw new InvalidChallengeError( - "Signer is not a valid address: " + err.message, + `Signer is not a valid address: ${ err.message}`, ); }