diff --git a/src/browser.ts b/src/browser.ts index 6af8aaf78..6befec18d 100644 --- a/src/browser.ts +++ b/src/browser.ts @@ -1,9 +1,9 @@ /* tslint:disable:no-var-requires */ -import axios from "axios"; - export * from "./index"; -export * as StellarBase from "@stellar/stellar-base"; // idk why axios is weird +export * as StellarBase from "@stellar/stellar-base"; + +import axios from "axios"; // idk why axios is weird export { axios }; export default module.exports; diff --git a/src/config.ts b/src/config.ts index a2aa1f1b1..946c793d8 100644 --- a/src/config.ts +++ b/src/config.ts @@ -1,11 +1,13 @@ 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; @@ -16,7 +18,7 @@ const defaultConfig: Configuration = { timeout: 0, }; -let config = { ...defaultConfig}; +let config = Object.assign({}, defaultConfig); /** * Global config class. @@ -80,7 +82,7 @@ class Config { * @returns {void} */ public static setDefault(): void { - config = { ...defaultConfig}; + config = Object.assign({}, defaultConfig); } } diff --git a/src/contract/assembled_transaction.ts b/src/contract/assembled_transaction.ts index 84ea47bcd..1f46824b9 100644 --- a/src/contract/assembled_transaction.ts +++ b/src/contract/assembled_transaction.ts @@ -388,7 +388,6 @@ export class AssembledTransaction { * ..., * simulate: false, * }) - * @param options */ static async build( options: AssembledTransactionOptions, @@ -510,9 +509,6 @@ 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, @@ -588,8 +584,6 @@ 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, @@ -652,10 +646,6 @@ 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 0424b9bf2..9e50327cd 100644 --- a/src/contract/basic_node_signer.ts +++ b/src/contract/basic_node_signer.ts @@ -8,8 +8,6 @@ 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 c574d5199..e0c298b4a 100644 --- a/src/contract/client.ts +++ b/src/contract/client.ts @@ -13,8 +13,6 @@ 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 */ @@ -55,6 +53,7 @@ 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". @@ -77,6 +76,7 @@ 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,6 +96,7 @@ 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 b6575d7d8..d6f275d78 100644 --- a/src/contract/sent_transaction.ts +++ b/src/contract/sent_transaction.ts @@ -70,8 +70,6 @@ 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 80b141efd..937875fbb 100644 --- a/src/contract/spec.ts +++ b/src/contract/spec.ts @@ -14,14 +14,9 @@ export interface Union { values?: T; } -/** - * - * @param args - * @param input - */ function readObj(args: object, input: xdr.ScSpecFunctionInputV0): any { - const inputName = input.name().toString(); - const entry = Object.entries(args).find(([name, _]) => name === inputName); + let inputName = input.name().toString(); + let entry = Object.entries(args).find(([name, _]) => name === inputName); if (!entry) { throw new Error(`Missing field ${inputName}`); } @@ -31,6 +26,7 @@ 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 @@ -57,14 +53,16 @@ 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"); } - const entry = entries[0]; + let entry = entries[0]; if (typeof entry === "string") { this.entries = (entries as string[]).map((s) => xdr.ScSpecEntry.fromXDR(s, "base64"), @@ -76,7 +74,9 @@ export class Spec { /** * Gets the XDR functions from the spec. + * * @returns {xdr.ScSpecFunctionV0[]} all contract functions + * */ funcs(): xdr.ScSpecFunctionV0[] { return this.entries @@ -87,15 +87,16 @@ 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 { - const entry = this.findEntry(name); + let entry = this.findEntry(name); if ( entry.switch().value !== xdr.ScSpecEntryKind.scSpecEntryFunctionV0().value ) { @@ -106,10 +107,13 @@ 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 = { @@ -120,7 +124,7 @@ export class Spec { * ``` */ funcArgsToScVals(name: string, args: object): xdr.ScVal[] { - const fn = this.getFunc(name); + let fn = this.getFunc(name); return fn .inputs() .map((input) => this.nativeToScVal(readObj(args, input), input.type())); @@ -128,10 +132,13 @@ 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 @@ -139,14 +146,14 @@ export class Spec { * ``` */ funcResToNative(name: string, val_or_base64: xdr.ScVal | string): any { - const val = + let val = typeof val_or_base64 === "string" ? xdr.ScVal.fromXDR(val_or_base64, "base64") : val_or_base64; - const func = this.getFunc(name); - const outputs = func.outputs(); + let func = this.getFunc(name); + let outputs = func.outputs(); if (outputs.length === 0) { - const type = val.switch(); + let type = val.switch(); if (type.value !== xdr.ScValType.scvVoid().value) { throw new Error(`Expected void, got ${type.name}`); } @@ -155,7 +162,7 @@ export class Spec { if (outputs.length > 1) { throw new Error(`Multiple outputs not supported`); } - const output = outputs[0]; + let output = outputs[0]; if (output.switch().value === xdr.ScSpecType.scSpecTypeResult().value) { return new Ok(this.scValToNative(val, output.result().okType())); } @@ -164,12 +171,14 @@ 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 { - const entry = this.entries.find( + let entry = this.entries.find( (entry) => entry.value().name().toString() === name, ); if (!entry) { @@ -180,20 +189,22 @@ 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 { - const t: xdr.ScSpecType = ty.switch(); - const {value} = t; + let t: xdr.ScSpecType = ty.switch(); + let value = t.value; if (t.value === xdr.ScSpecType.scSpecTypeUdt().value) { - const udt = ty.udt(); + let udt = ty.udt(); return this.nativeToUdt(val, udt.name().toString()); } if (value === xdr.ScSpecType.scSpecTypeOption().value) { - const opt = ty.option(); + let opt = ty.option(); if (val === undefined) { return xdr.ScVal.scvVoid(); } @@ -238,17 +249,17 @@ export class Spec { const copy = Uint8Array.from(val); switch (value) { case xdr.ScSpecType.scSpecTypeBytesN().value: { - const bytes_n = ty.bytesN(); + let 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( @@ -259,15 +270,15 @@ export class Spec { if (Array.isArray(val)) { switch (value) { case xdr.ScSpecType.scSpecTypeVec().value: { - const vec = ty.vec(); - const elementType = vec.elementType(); + let vec = ty.vec(); + let elementType = vec.elementType(); return xdr.ScVal.scvVec( val.map((v) => this.nativeToScVal(v, elementType)), ); } case xdr.ScSpecType.scSpecTypeTuple().value: { - const tup = ty.tuple(); - const valTypes = tup.valueTypes(); + let tup = ty.tuple(); + let valTypes = tup.valueTypes(); if (val.length !== valTypes.length) { throw new TypeError( `Tuple expects ${valTypes.length} values, but ${val.length} were provided`, @@ -278,13 +289,13 @@ export class Spec { ); } case xdr.ScSpecType.scSpecTypeMap().value: { - const map = ty.map(); - const keyType = map.keyType(); - const valueType = map.valueType(); + let map = ty.map(); + let keyType = map.keyType(); + let valueType = map.valueType(); return xdr.ScVal.scvMap( val.map((entry) => { - const key = this.nativeToScVal(entry[0], keyType); - const val = this.nativeToScVal(entry[1], valueType); + let key = this.nativeToScVal(entry[0], keyType); + let val = this.nativeToScVal(entry[1], valueType); return new xdr.ScMapEntry({ key, val }); }), ); @@ -300,15 +311,15 @@ export class Spec { if (value !== xdr.ScSpecType.scSpecTypeMap().value) { throw new TypeError(`Type ${ty} was not map, but value was Map`); } - const scMap = ty.map(); - const map = val as Map; - const entries: xdr.ScMapEntry[] = []; - const values = map.entries(); + let scMap = ty.map(); + let map = val as Map; + let entries: xdr.ScMapEntry[] = []; + let values = map.entries(); let res = values.next(); while (!res.done) { - const [k, v] = res.value; - const key = this.nativeToScVal(k, scMap.keyType()); - const val = this.nativeToScVal(v, scMap.valueType()); + let [k, v] = res.value; + let key = this.nativeToScVal(k, scMap.keyType()); + let val = this.nativeToScVal(v, scMap.valueType()); entries.push(new xdr.ScMapEntry({ key, val })); res = values.next(); } @@ -380,7 +391,7 @@ export class Spec { } private nativeToUdt(val: any, name: string): xdr.ScVal { - const entry = this.findEntry(name); + let entry = this.findEntry(name); switch (entry.switch()) { case xdr.ScSpecEntryKind.scSpecEntryUdtEnumV0(): if (typeof val !== "number") { @@ -402,28 +413,28 @@ export class Spec { val: Union, union_: xdr.ScSpecUdtUnionV0, ): xdr.ScVal { - const entry_name = val.tag; - const case_ = union_.cases().find((entry) => { - const case_ = entry.value().name().toString(); + let entry_name = val.tag; + let case_ = union_.cases().find((entry) => { + let case_ = entry.value().name().toString(); return case_ === entry_name; }); if (!case_) { throw new TypeError(`no such enum entry: ${entry_name} in ${union_}`); } - const key = xdr.ScVal.scvSymbol(entry_name); + let key = xdr.ScVal.scvSymbol(entry_name); switch (case_.switch()) { case xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseVoidV0(): { return xdr.ScVal.scvVec([key]); } case xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0(): { - const types = case_.tupleCase().type(); + let 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}`, ); } - const scvals = val.values.map((v, i) => + let scvals = val.values.map((v, i) => this.nativeToScVal(v, types[i]), ); scvals.unshift(key); @@ -437,7 +448,7 @@ export class Spec { } private nativeToStruct(val: any, struct: xdr.ScSpecUdtStructV0): xdr.ScVal { - const fields = struct.fields(); + let fields = struct.fields(); if (fields.some(isNumeric)) { if (!fields.every(isNumeric)) { throw new Error( @@ -450,7 +461,7 @@ export class Spec { } return xdr.ScVal.scvMap( fields.map((field) => { - const name = field.name().toString(); + let name = field.name().toString(); return new xdr.ScMapEntry({ key: this.nativeToScVal(name, xdr.ScSpecTypeDef.scSpecTypeSymbol()), val: this.nativeToScVal(val[name], field.type()), @@ -468,9 +479,11 @@ 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 { @@ -479,14 +492,16 @@ 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 { - const t = typeDef.switch(); - const {value} = t; + let t = typeDef.switch(); + let value = t.value; if (value === xdr.ScSpecType.scSpecTypeUdt().value) { return this.scValUdtToNative(scv, typeDef.udt()); } @@ -511,13 +526,13 @@ export class Spec { case xdr.ScValType.scvVec().value: { if (value == xdr.ScSpecType.scSpecTypeVec().value) { - const vec = typeDef.vec(); + let vec = typeDef.vec(); return (scv.vec() ?? []).map((elm) => this.scValToNative(elm, vec.elementType()), ) as T; - } if (value == xdr.ScSpecType.scSpecTypeTuple().value) { - const tuple = typeDef.tuple(); - const valTypes = tuple.valueTypes(); + } else if (value == xdr.ScSpecType.scSpecTypeTuple().value) { + let tuple = typeDef.tuple(); + let valTypes = tuple.valueTypes(); return (scv.vec() ?? []).map((elm, i) => this.scValToNative(elm, valTypes[i]), ) as T; @@ -529,12 +544,12 @@ export class Spec { return Address.fromScVal(scv).toString() as T; case xdr.ScValType.scvMap().value: { - const map = scv.map() ?? []; + let map = scv.map() ?? []; if (value == xdr.ScSpecType.scSpecTypeMap().value) { - const type_ = typeDef.map(); - const keyType = type_.keyType(); - const valueType = type_.valueType(); - const res = map.map((entry) => [ + let type_ = typeDef.map(); + let keyType = type_.keyType(); + let valueType = type_.valueType(); + let res = map.map((entry) => [ this.scValToNative(entry.key(), keyType), this.scValToNative(entry.val(), valueType), ]) as T; @@ -588,7 +603,7 @@ export class Spec { } private scValUdtToNative(scv: xdr.ScVal, udt: xdr.ScSpecTypeUdt): any { - const entry = this.findEntry(udt.name().toString()); + let entry = this.findEntry(udt.name().toString()); switch (entry.switch()) { case xdr.ScSpecEntryKind.scSpecEntryUdtEnumV0(): return this.enumToNative(scv); @@ -604,7 +619,7 @@ export class Spec { } private unionToNative(val: xdr.ScVal, udt: xdr.ScSpecUdtUnionV0): any { - const vec = val.vec(); + let vec = val.vec(); if (!vec) { throw new Error(`${JSON.stringify(val, null, 2)} is not a vec`); } @@ -613,40 +628,39 @@ export class Spec { `${val} has length 0, but the there are at least one case in the union`, ); } - const name = vec[0].sym().toString(); + let name = vec[0].sym().toString(); if (vec[0].switch().value != xdr.ScValType.scvSymbol().value) { throw new Error(`{vec[0]} is not a symbol`); } - const entry = udt.cases().find(findCase(name)); + let entry = udt.cases().find(findCase(name)); if (!entry) { throw new Error( `failed to find entry ${name} in union {udt.name().toString()}`, ); } - const res: Union = { tag: name }; + let res: Union = { tag: name }; if ( entry.switch().value === xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0().value ) { - const tuple = entry.tupleCase(); - const ty = tuple.type(); - const values = ty.map((entry, i) => this.scValToNative(vec![i + 1], entry)); + let tuple = entry.tupleCase(); + let ty = tuple.type(); + let 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 { - const res: any = {}; - const fields = udt.fields(); + let res: any = {}; + let fields = udt.fields(); if (fields.some(isNumeric)) { - const r = val + let r = val .vec() ?.map((entry, i) => this.scValToNative(entry, fields[i].type())); return r; } val.map()?.forEach((entry, i) => { - const field = fields[i]; + let field = fields[i]; res[field.name().toString()] = this.scValToNative( entry.val(), field.type(), @@ -659,13 +673,15 @@ export class Spec { if (scv.switch().value !== xdr.ScValType.scvU32().value) { throw new Error(`Enum must have a u32 value`); } - const num = scv.u32(); + let 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 @@ -681,32 +697,34 @@ 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 { - const definitions: { [key: string]: JSONSchema7Definition } = {}; - for (const entry of this.entries) { + let definitions: { [key: string]: JSONSchema7Definition } = {}; + for (let entry of this.entries) { switch (entry.switch().value) { case xdr.ScSpecEntryKind.scSpecEntryUdtEnumV0().value: { - const udt = entry.udtEnumV0(); + let udt = entry.udtEnumV0(); definitions[udt.name().toString()] = enumToJsonSchema(udt); break; } case xdr.ScSpecEntryKind.scSpecEntryUdtStructV0().value: { - const udt = entry.udtStructV0(); + let udt = entry.udtStructV0(); definitions[udt.name().toString()] = structToJsonSchema(udt); break; } case xdr.ScSpecEntryKind.scSpecEntryUdtUnionV0().value: - const udt = entry.udtUnionV0(); + let udt = entry.udtUnionV0(); definitions[udt.name().toString()] = unionToJsonSchema(udt); break; case xdr.ScSpecEntryKind.scSpecEntryFunctionV0().value: { - const fn = entry.functionV0(); - const fnName = fn.name().toString(); - const { input } = functionToJsonSchema(fn); + let fn = entry.functionV0(); + let fnName = fn.name().toString(); + let { input } = functionToJsonSchema(fn); // @ts-ignore definitions[fnName] = input; break; @@ -716,22 +734,17 @@ export class Spec { } } } - const res: JSONSchema7 = { + let 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: @@ -739,7 +752,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: { - const addr = Address.fromString(str as string); + let addr = Address.fromString(str as string); return xdr.ScVal.scvAddress(addr.toScAddress()); } case xdr.ScSpecType.scSpecTypeU64().value: @@ -763,27 +776,19 @@ 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: { - const tuple = entry.tupleCase(); + let tuple = entry.tupleCase(); return tuple.name().toString() === name; } case xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseVoidV0().value: { - const void_case = entry.voidCase(); + let void_case = entry.voidCase(); return void_case.name().toString() === name; } default: @@ -864,8 +869,8 @@ const PRIMITIVE_DEFINITONS: { [key: string]: JSONSchema7Definition } = { * @returns {JSONSchema7} a schema describing the type */ function typeRef(typeDef: xdr.ScSpecTypeDef): JSONSchema7 { - const t = typeDef.switch(); - const {value} = t; + let t = typeDef.switch(); + let value = t.value; let ref; switch (value) { case xdr.ScSpecType.scSpecTypeVal().value: { @@ -941,7 +946,7 @@ function typeRef(typeDef: xdr.ScSpecTypeDef): JSONSchema7 { break; } case xdr.ScSpecType.scSpecTypeOption().value: { - const opt = typeDef.option(); + let opt = typeDef.option(); return typeRef(opt.valueType()); } case xdr.ScSpecType.scSpecTypeResult().value: { @@ -949,16 +954,16 @@ function typeRef(typeDef: xdr.ScSpecTypeDef): JSONSchema7 { break; } case xdr.ScSpecType.scSpecTypeVec().value: { - const arr = typeDef.vec(); - const ref = typeRef(arr.elementType()); + let arr = typeDef.vec(); + let ref = typeRef(arr.elementType()); return { type: "array", items: ref, }; } case xdr.ScSpecType.scSpecTypeMap().value: { - const map = typeDef.map(); - const items = [typeRef(map.keyType()), typeRef(map.valueType())]; + let map = typeDef.map(); + let items = [typeRef(map.keyType()), typeRef(map.valueType())]; return { type: "array", items: { @@ -970,21 +975,21 @@ function typeRef(typeDef: xdr.ScSpecTypeDef): JSONSchema7 { }; } case xdr.ScSpecType.scSpecTypeTuple().value: { - const tuple = typeDef.tuple(); - const minItems = tuple.valueTypes().length; - const maxItems = minItems; - const items = tuple.valueTypes().map(typeRef); + let tuple = typeDef.tuple(); + let minItems = tuple.valueTypes().length; + let maxItems = minItems; + let items = tuple.valueTypes().map(typeRef); return { type: "array", items, minItems, maxItems }; } case xdr.ScSpecType.scSpecTypeBytesN().value: { - const arr = typeDef.bytesN(); + let arr = typeDef.bytesN(); return { $ref: "#/definitions/DataUrl", maxLength: arr.n(), }; } case xdr.ScSpecType.scSpecTypeUdt().value: { - const udt = typeDef.udt(); + let udt = typeDef.udt(); ref = udt.name().toString(); break; } @@ -994,27 +999,19 @@ 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 { - const fields = udt.fields(); + let fields = udt.fields(); if (fields.some(isNumeric)) { if (!fields.every(isNumeric)) { throw new Error( "mixed numeric and non-numeric field names are not allowed", ); } - const items = fields.map((_, i) => typeRef(fields[i].type())); + let items = fields.map((_, i) => typeRef(fields[i].type())); return { type: "array", items, @@ -1022,9 +1019,9 @@ function structToJsonSchema(udt: xdr.ScSpecUdtStructV0): object { maxItems: fields.length, }; } - const description = udt.doc().toString(); - const { properties, required }: any = args_and_required(fields); - properties.additionalProperties = false; + let description = udt.doc().toString(); + let { properties, required }: any = args_and_required(fields); + properties["additionalProperties"] = false; return { description, properties, @@ -1033,37 +1030,29 @@ function structToJsonSchema(udt: xdr.ScSpecUdtStructV0): object { }; } -/** - * - * @param input - */ function args_and_required( input: { type: () => xdr.ScSpecTypeDef; name: () => string | Buffer }[], ): { properties: object; required?: string[] } { - const properties: any = {}; - const required: string[] = []; - for (const arg of input) { - const type_ = arg.type(); - const name = arg.name().toString(); + let properties: any = {}; + let required: string[] = []; + for (let arg of input) { + let type_ = arg.type(); + let name = arg.name().toString(); properties[name] = typeRef(type_); if (isRequired(type_)) { required.push(name); } } - const res: { properties: object; required?: string[] } = { properties }; + let res: { properties: object; required?: string[] } = { properties }; if (required.length > 0) { res.required = required; } return res; } -/** - * - * @param func - */ function functionToJsonSchema(func: xdr.ScSpecFunctionV0): Func { - const { properties, required }: any = args_and_required(func.inputs()); - const args: any = { + let { properties, required }: any = args_and_required(func.inputs()); + let args: any = { additionalProperties: false, properties, type: "object", @@ -1071,17 +1060,17 @@ function functionToJsonSchema(func: xdr.ScSpecFunctionV0): Func { if (required?.length > 0) { args.required = required; } - const input: Partial = { + let input: Partial = { properties: { args, }, }; - const outputs = func.outputs(); - const output: Partial = + let outputs = func.outputs(); + let output: Partial = outputs.length > 0 ? typeRef(outputs[0]) : typeRef(xdr.ScSpecTypeDef.scSpecTypeVoid()); - const description = func.doc().toString(); + let description = func.doc().toString(); if (description.length > 0) { input.description = description; } @@ -1093,19 +1082,15 @@ function functionToJsonSchema(func: xdr.ScSpecFunctionV0): Func { }; } -/** - * - * @param udt - */ function unionToJsonSchema(udt: xdr.ScSpecUdtUnionV0): any { - const description = udt.doc().toString(); - const cases = udt.cases(); - const oneOf: any[] = []; - for (const case_ of cases) { + let description = udt.doc().toString(); + let cases = udt.cases(); + let oneOf: any[] = []; + for (let case_ of cases) { switch (case_.switch().value) { case xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseVoidV0().value: { - const c = case_.voidCase(); - const title = c.name().toString(); + let c = case_.voidCase(); + let title = c.name().toString(); oneOf.push({ type: "object", title, @@ -1118,8 +1103,8 @@ function unionToJsonSchema(udt: xdr.ScSpecUdtUnionV0): any { break; } case xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0().value: { - const c = case_.tupleCase(); - const title = c.name().toString(); + let c = case_.tupleCase(); + let title = c.name().toString(); oneOf.push({ type: "object", title, @@ -1137,7 +1122,7 @@ function unionToJsonSchema(udt: xdr.ScSpecUdtUnionV0): any { } } - const res: any = { + let res: any = { oneOf, }; if (description.length > 0) { @@ -1146,17 +1131,13 @@ function unionToJsonSchema(udt: xdr.ScSpecUdtUnionV0): any { return res; } -/** - * - * @param udt - */ function enumToJsonSchema(udt: xdr.ScSpecUdtEnumV0): any { - 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(); + 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(); oneOf.push({ description, title, @@ -1165,7 +1146,7 @@ function enumToJsonSchema(udt: xdr.ScSpecUdtEnumV0): any { }); } - const res: any = { oneOf }; + let res: any = { oneOf }; if (description.length > 0) { res.description = description; } diff --git a/src/contract/utils.ts b/src/contract/utils.ts index f8db49621..44e7b8b02 100644 --- a/src/contract/utils.ts +++ b/src/contract/utils.ts @@ -9,11 +9,6 @@ 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 */ @@ -92,7 +87,6 @@ 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 */ @@ -103,7 +97,6 @@ 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 38a70e85e..b84f72162 100644 --- a/src/errors.ts +++ b/src/errors.ts @@ -10,7 +10,6 @@ export class NetworkError extends Error { statusText?: string; url?: string; }; - public __proto__: NetworkError; constructor(message: string, response: any) { @@ -73,12 +72,10 @@ 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 53bc02c8c..06d88fc87 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. - * @class + * @constructor * @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,19 +26,20 @@ 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 */ @@ -48,24 +49,25 @@ 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`) @@ -73,9 +75,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, @@ -211,7 +213,7 @@ export class FederationServer { } private async _sendRequest(url: URI) { - const {timeout} = this; + const timeout = this.timeout; return axios .get(url.toString(), { diff --git a/src/horizon/account_call_builder.ts b/src/horizon/account_call_builder.ts index dc02ad2a8..06997053a 100644 --- a/src/horizon/account_call_builder.ts +++ b/src/horizon/account_call_builder.ts @@ -5,10 +5,11 @@ 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 - * @augments CallBuilder - * @class + * @extends CallBuilder + * @constructor * @param {string} serverUrl Horizon server URL. */ export class AccountCallBuilder extends CallBuilder< @@ -22,6 +23,7 @@ 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 @@ -68,6 +70,7 @@ 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 65016737f..376e9a197 100644 --- a/src/horizon/account_response.ts +++ b/src/horizon/account_response.ts @@ -10,67 +10,46 @@ 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 591bf7a37..29d63200a 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 - * @class - * @augments CallBuilder + * @constructor + * @extends 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 010648436..d8c6f8ec4 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 -const EventSource: Constructable = anyGlobal.EventSource ?? +let EventSource: Constructable = anyGlobal.EventSource ?? anyGlobal.window?.EventSource ?? require("eventsource"); @@ -38,11 +38,8 @@ export class CallBuilder< | ServerApi.CollectionPage > { protected url: URI; - public filter: string[][]; - protected originalSegments: string[]; - protected neighborRoot: string; constructor(serverUrl: URI, neighborRoot: string = "") { @@ -62,22 +59,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 @@ -85,10 +82,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(); @@ -198,7 +195,6 @@ 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 */ @@ -224,8 +220,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 { @@ -236,14 +232,16 @@ 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: + * 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)`. * - * 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 { @@ -276,7 +274,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 ae98c6f40..bf515702a 100644 --- a/src/horizon/claimable_balances_call_builder.ts +++ b/src/horizon/claimable_balances_call_builder.ts @@ -5,10 +5,11 @@ 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 - * @class - * @augments CallBuilder + * @constructor + * @extends CallBuilder * @param {string} serverUrl Horizon server URL. */ export class ClaimableBalanceCallBuilder extends CallBuilder< @@ -21,6 +22,7 @@ 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 @@ -37,6 +39,7 @@ 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 @@ -48,6 +51,7 @@ 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 @@ -59,8 +63,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 f6347de76..d6db8cc28 100644 --- a/src/horizon/effect_call_builder.ts +++ b/src/horizon/effect_call_builder.ts @@ -4,10 +4,11 @@ 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 - * @augments CallBuilder + * @extends CallBuilder * @see [All Effects](https://developers.stellar.org/api/resources/effects/) - * @class + * @constructor * @param {string} serverUrl Horizon server URL. */ export class EffectCallBuilder extends CallBuilder< @@ -62,6 +63,7 @@ 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 154681f8f..a76da401f 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"); +export const version = require("../../package.json").version; export interface ServerTime { serverTime: number; @@ -30,16 +30,12 @@ export const AxiosClient = axios.create({ }, }); -/** - * - * @param ms - */ function _toSeconds(ms: number): number { return Math.floor(ms / 1000); } AxiosClient.interceptors.response.use( - (response: AxiosResponse) => { + function interceptorHorizonResponse(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 8708940d9..5e74a85b5 100644 --- a/src/horizon/ledger_call_builder.ts +++ b/src/horizon/ledger_call_builder.ts @@ -4,10 +4,11 @@ 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/) - * @class + * @constructor * @class LedgerCallBuilder - * @augments CallBuilder + * @extends 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 0657fd62f..f6c24b1f5 100644 --- a/src/horizon/liquidity_pool_call_builder.ts +++ b/src/horizon/liquidity_pool_call_builder.ts @@ -6,9 +6,10 @@ 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 - * @augments CallBuilder - * @class + * @extends CallBuilder + * @constructor * @param {string} serverUrl Horizon server URL. */ export class LiquidityPoolCallBuilder extends CallBuilder< @@ -21,6 +22,7 @@ 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 @@ -35,6 +37,7 @@ 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 */ @@ -45,6 +48,7 @@ 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 15b76a8a7..4d40b1a4b 100644 --- a/src/horizon/offer_call_builder.ts +++ b/src/horizon/offer_call_builder.ts @@ -5,10 +5,11 @@ 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 - * @class - * @augments CallBuilder + * @constructor + * @extends CallBuilder * @param {string} serverUrl Horizon server URL. */ export class OfferCallBuilder extends CallBuilder< @@ -34,6 +35,7 @@ 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 @@ -91,6 +93,7 @@ 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 e9a7dd3a4..e7573e7ba 100644 --- a/src/horizon/operation_call_builder.ts +++ b/src/horizon/operation_call_builder.ts @@ -4,10 +4,11 @@ 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 - * @class - * @augments CallBuilder + * @constructor + * @extends CallBuilder * @param {string} serverUrl Horizon server URL. */ export class OperationCallBuilder extends CallBuilder< @@ -57,6 +58,7 @@ 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 @@ -77,6 +79,7 @@ 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 */ @@ -86,7 +89,8 @@ 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 80108ac81..4999e07d8 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/) - * @augments CallBuilder + * @extends 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 1e5c8cb6b..82e103fb1 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/) - * @class - * @augments CallBuilder + * @constructor + * @extends 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 3e29a1b7c..48c92106d 100644 --- a/src/horizon/server.ts +++ b/src/horizon/server.ts @@ -50,10 +50,6 @@ 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(); } @@ -61,7 +57,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. - * @class + * @constructor * @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. @@ -135,10 +131,8 @@ export class Server { * // earlier does the trick! * .build(); * ``` - * @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! + * @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! * 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. @@ -168,7 +162,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 this.fetchTimebounds(seconds, true); + return await this.fetchTimebounds(seconds, true); } /** @@ -209,86 +203,87 @@ 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. @@ -382,8 +377,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(), ); } @@ -493,7 +488,9 @@ export class Server { .filter((result: any) => !!result); } - return { ...response.data, offerResults: hasManageOffer ? offerResults : undefined,}; + return Object.assign({}, response.data, { + offerResults: hasManageOffer ? offerResults : undefined, + }); }) .catch((response) => { if (response instanceof Error) { @@ -598,9 +595,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 @@ -610,6 +607,7 @@ 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. @@ -637,6 +635,7 @@ 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. @@ -693,7 +692,9 @@ 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. */ @@ -745,6 +746,7 @@ 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 @@ -776,7 +778,7 @@ export class Server { default: continue; } - const {destination} = operation; + const destination = operation.destination; if (destinations.has(destination)) { continue; } diff --git a/src/horizon/server_api.ts b/src/horizon/server_api.ts index b567498e7..049f98b04 100644 --- a/src/horizon/server_api.ts +++ b/src/horizon/server_api.ts @@ -182,7 +182,6 @@ 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 f8857e05a..b44876780 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/) - * @augments CallBuilder + * @extends 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 674bcd867..da840374b 100644 --- a/src/horizon/strict_send_path_call_builder.ts +++ b/src/horizon/strict_send_path_call_builder.ts @@ -22,11 +22,12 @@ 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/) - * @augments CallBuilder + * @extends 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 695f364a7..8dfff4f69 100644 --- a/src/horizon/trade_aggregation_call_builder.ts +++ b/src/horizon/trade_aggregation_call_builder.ts @@ -17,9 +17,10 @@ const allowedResolutions = [ /** * Trade Aggregations facilitate efficient gathering of historical trade data. * Do not create this object directly, use {@link Server#tradeAggregation}. + * * @class TradeAggregationCallBuilder - * @augments CallBuilder - * @class + * @extends CallBuilder + * @constructor * @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 daf229aa8..8c601454d 100644 --- a/src/horizon/trades_call_builder.ts +++ b/src/horizon/trades_call_builder.ts @@ -5,9 +5,10 @@ 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 - * @augments CallBuilder - * @class + * @extends CallBuilder + * @constructor * @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 4d7583925..831c4ee6f 100644 --- a/src/horizon/transaction_call_builder.ts +++ b/src/horizon/transaction_call_builder.ts @@ -4,10 +4,11 @@ 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 - * @augments CallBuilder + * @extends CallBuilder * @see [All Transactions](https://developers.stellar.org/api/resources/transactions/) - * @class + * @constructor * @param {string} serverUrl Horizon server URL. */ export class TransactionCallBuilder extends CallBuilder< @@ -66,6 +67,7 @@ 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 844e76d63..76708718c 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 f7d0c8af7..7742295d8 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 7331664bb..9a0de5000 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 bd2bd4ad9..3c8d7806f 100644 --- a/src/rpc/api.ts +++ b/src/rpc/api.ts @@ -33,8 +33,7 @@ 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; @@ -223,12 +222,13 @@ 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,30 +291,18 @@ 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 { @@ -325,10 +313,6 @@ export namespace Api { ); } - /** - * - * @param sim - */ export function isSimulationRaw( sim: | Api.SimulateTransactionResponse diff --git a/src/rpc/axios.ts b/src/rpc/axios.ts index ba154a315..bf19ff7d9 100644 --- a/src/rpc/axios.ts +++ b/src/rpc/axios.ts @@ -1,8 +1,7 @@ import axios from 'axios'; /* tslint:disable-next-line:no-var-requires */ -export const {version} = require('../../package.json'); - +export const version = require('../../package.json').version; 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 d08334f21..a5ce47b04 100644 --- a/src/rpc/browser.ts +++ b/src/rpc/browser.ts @@ -1,9 +1,9 @@ /* tslint:disable:no-var-requires */ -import axios from 'axios'; - export * from './index'; -export * as StellarBase from '@stellar/stellar-base'; // idk why axios is weird +export * as StellarBase from '@stellar/stellar-base'; + +import axios from 'axios'; // idk why axios is weird export { axios }; export default module.exports; diff --git a/src/rpc/jsonrpc.ts b/src/rpc/jsonrpc.ts index 388af1628..bd93ebbef 100644 --- a/src/rpc/jsonrpc.ts +++ b/src/rpc/jsonrpc.ts @@ -26,12 +26,7 @@ export interface Error { data?: E; } -/** - * Sends the jsonrpc 'params' as a single 'param' object (no array support). - * @param url - * @param method - * @param param - */ +/** Sends the jsonrpc 'params' as a single 'param' object (no array support). */ export async function postObject( url: string, method: string, @@ -53,11 +48,6 @@ 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 9dc1ae561..8ff1d1c6d 100644 --- a/src/rpc/parsers.ts +++ b/src/rpc/parsers.ts @@ -1,10 +1,6 @@ import { xdr, Contract, SorobanDataBuilder } from '@stellar/stellar-base'; import { Api } from './api'; -/** - * - * @param r - */ export function parseRawSendTransaction( r: Api.RawSendTransactionResponse ): Api.SendTransactionResponse { @@ -12,7 +8,7 @@ export function parseRawSendTransaction( delete r.errorResultXdr; delete r.diagnosticEventsXdr; - if (errorResultXdr) { + if (!!errorResultXdr) { return { ...r, ...( @@ -30,10 +26,6 @@ export function parseRawSendTransaction( return { ...r } as Api.BaseSendTransactionResponse; } -/** - * - * @param r - */ export function parseRawEvents( r: Api.RawGetEventsResponse ): Api.GetEventsResponse { @@ -54,10 +46,6 @@ export function parseRawEvents( }; } -/** - * - * @param raw - */ export function parseRawLedgerEntries( raw: Api.RawGetLedgerEntriesResponse ): Api.GetLedgerEntriesResponse { @@ -85,10 +73,12 @@ 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". */ @@ -104,7 +94,7 @@ export function parseRawSimulation( } // shared across all responses - const base: Api.BaseSimulateTransactionResponse = { + let base: Api.BaseSimulateTransactionResponse = { _parsed: true, id: sim.id, latestLedger: sim.latestLedger, @@ -123,11 +113,6 @@ export function parseRawSimulation( return parseSuccessful(sim, base); } -/** - * - * @param sim - * @param partial - */ function parseSuccessful( sim: Api.RawSimulateTransactionResponse, partial: Api.BaseSimulateTransactionResponse @@ -143,15 +128,17 @@ 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) => ({ + result: sim.results!.map((row) => { + return { 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 ae38be7d4..e3c518efb 100644 --- a/src/rpc/server.ts +++ b/src/rpc/server.ts @@ -55,7 +55,9 @@ export namespace Server { /** * Handles the network connection to a Soroban RPC instance, exposing an * interface for requests to that instance. - * @class + * + * @constructor + * * @param {string} serverURL Soroban-RPC Server URL (ex. * `http://localhost:8000/soroban/rpc`). * @param {object} [opts] Options object @@ -63,6 +65,7 @@ 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 { @@ -92,9 +95,12 @@ 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"; @@ -123,9 +129,11 @@ 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) => { @@ -145,16 +153,20 @@ 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] the "durability + * @param {Durability} [durability=Durability.Persistent] 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"; @@ -197,7 +209,7 @@ export class Server { throw new TypeError(`invalid durability: ${durability}`); } - const contractKey = xdr.LedgerKey.contractData( + let contractKey = xdr.LedgerKey.contractData( new xdr.LedgerKeyContractData({ key, contract: scAddress, @@ -229,11 +241,15 @@ 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 => { @@ -268,11 +284,14 @@ 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 => { @@ -312,9 +331,12 @@ 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 @@ -354,9 +376,12 @@ 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"; @@ -425,9 +450,11 @@ 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({ @@ -475,8 +502,10 @@ 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) => { @@ -486,14 +515,16 @@ export class Server { * }); */ public async getNetwork(): Promise { - return jsonrpc.postObject(this.serverURL.toString(), 'getNetwork'); + return await 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) => { @@ -509,20 +540,22 @@ 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); @@ -588,6 +621,7 @@ 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}, @@ -598,12 +632,13 @@ 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} @@ -655,9 +690,11 @@ 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 @@ -707,17 +744,21 @@ 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 @@ -763,10 +804,6 @@ export class Server { } } -/** - * - * @param meta - */ function findCreatedAccountSequenceInTransactionMeta( meta: xdr.TransactionMeta ): string { diff --git a/src/rpc/transaction.ts b/src/rpc/transaction.ts index 95180266b..c75f333b4 100644 --- a/src/rpc/transaction.ts +++ b/src/rpc/transaction.ts @@ -10,14 +10,18 @@ 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} */ @@ -43,7 +47,7 @@ export function assembleTransaction( ); } - const success = parseRawSimulation(simulation); + let success = parseRawSimulation(simulation); if (!Api.isSimulationSuccess(success)) { throw new Error(`simulation incorrect: ${JSON.stringify(success)}`); } @@ -90,10 +94,6 @@ 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 578b6dd87..af4bb76a2 100644 --- a/src/rpc/utils.ts +++ b/src/rpc/utils.ts @@ -1,10 +1,5 @@ // 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 efeb6fd33..ba0c965bf 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; +const CancelToken = axios.CancelToken; /** Resolver allows resolving `stellar.toml` files. */ export class Resolver { diff --git a/src/utils.ts b/src/utils.ts index fbf64c0a8..3186a51ff 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 3adbcd6bf..3e6d13c73 100644 --- a/src/webauth/utils.ts +++ b/src/webauth/utils.ts @@ -20,14 +20,16 @@ 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] Challenge duration (default to 5 minutes). + * @param {number} [timeout=300] 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 @@ -41,9 +43,11 @@ 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' * @@ -140,8 +144,10 @@ 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 @@ -152,10 +158,12 @@ 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( @@ -354,13 +362,15 @@ 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 @@ -376,9 +386,11 @@ 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'; @@ -478,12 +490,14 @@ 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 @@ -498,6 +512,7 @@ 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'; @@ -557,8 +572,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, ); } @@ -630,7 +645,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() + "'", ); } @@ -668,11 +683,13 @@ 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"); @@ -695,12 +712,14 @@ 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(); @@ -732,7 +751,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, ); }