UNPKG

@fioprotocol/fiosdk

Version:

The Foundation for Interwallet Operability (FIO) is a consortium of leading blockchain wallets, exchanges and payments providers that seeks to accelerate blockchain adoption by reducing the risk, complexity, and inconvenience of sending and receiving cryp

1,368 lines (1,293 loc) 137 kB
import {Ecc, Fio} from '@fioprotocol/fiojs' import Big from 'big.js'; import { AbiResponse, Account, AccountResponse, Action, AddBundledTransactionsOptions, AddBundledTransactionsResponse, AddPublicAddressesOptions, AddPublicAddressesResponse, AddPublicAddressOptions, AvailabilityResponse, BurnFioAddressOptions, BurnFioAddressResponse, CancelFundsRequestOptions, CancelFundsRequestResponse, CancelledFioRequestsDecryptedResponse, ContentType, GetEncryptKeyResponse, EndPoint, FetchJson, FioAddressesResponse, BalanceResponse, FioDomainsResponse, FioFeeResponse, FioLogger, FioNamesResponse, FioOracleFeesResponse, FioSdkOptions, RequestFundsResponse, GetAbiOptions, GetAccountOptions, GetAccountPubKeyResponse, GetAccountPubKeyOptions, GetCancelledFioRequestsOptions, GetEncryptKeyOptions, GetFeeForAddBundledTransactionsOptions, GetFeeForAddPublicAddressOptions, GetFeeForBurnFioAddressOptions, GetFeeForCancelFundsRequestOptions, GetFeeForNewFundsRequestOptions, GetFeeForRecordObtDataOptions, GetFeeForRejectFundsRequestOptions, GetFeeForRemoveAllPublicAddressesOptions, GetFeeForRemovePublicAddressesOptions, GetFeeForTransferFioAddressOptions, GetFeeForTransferFioDomainOptions, GetFeeForTransferLockedTokensOptions, GetFeeOptions, GetFioAddressesOptions, GetFioBalanceOptions, GetFioDomainsOptions, GetFioNamesOptions, GetFioPublicAddressOptions, GetGranteePermissionsOptions, GetGrantorPermissionsOptions, GetLocksOptions, GetNftsOptions, GetObjectPermissionsOptions, GetObtDataDecryptedResponse, GetObtDataOptions, GetOracleFeesOptions, GetPendingFioRequestsOptions, GetPublicAddressesOptions, GetPublicAddressOptions, GetReceivedFioRequestsOptions, GetSentFioRequestsOptions, IsAvailableOptions, LockPeriod, LocksResponse, NftsResponse, PendingFioRequestsDecryptedResponse, PermissionsResponse, PublicAddress, PublicAddressesResponse, PublicAddressResponse, PushTransactionOptions, ReceivedFioRequestsDecryptedResponse, RecordObtDataOptions, RecordObtDataResponse, RegisterFioAddressOptions, RegisterFioAddressResponse, RegisterFioDomainAddressOptions, RegisterFioDomainOptions, RegisterFioDomainResponse, RegisterOwnerFioAddressOptions, RegisterOwnerFioDomainOptions, RejectFundsRequestOptions, RejectFundsResponse, RemoveAllPublicAddressesOptions, RemoveAllPublicAddressesResponse, RemovePublicAddressesOptions, RemovePublicAddressesResponse, RenewFioAddressOptions, RenewFioAddressResponse, RenewFioDomainOptions, RenewFioDomainResponse, RequestFundsOptions, SentFioRequestsDecryptedResponse, SetFioDomainVisibilityOptions, SetFioDomainVisibilityResponse, StakeFioTokensOptions, TransactionResponse, TransferFioAddressOptions, TransferFioAddressResponse, TransferFioDomainOptions, TransferFioDomainResponse, TransferLockedTokensOptions, TransferLockedTokensResponse, TransferTokensResponse, TransferTokensOptions, UnStakeFioTokensOptions, ValidationError, } from './entities' import * as queries from './transactions/queries' import {Transactions, RequestConfig} from './transactions/Transactions' import * as requests from './transactions/signed' import {SignedTransaction} from './transactions/signed/SignedTransaction' import {ClassMethodsToExcludeFromProxy} from './utils/constants' import * as fioConstants from './utils/constants' import {cleanupObject, getCipherContent, getUnCipherContent, resolveOptions} from './utils/utils' import {allRules, validate} from './utils/validation' export * from './utils/validation' export * from './entities' export { fioConstants } export enum GenericAction { getFioPublicKey = 'getFioPublicKey', getAccount = 'getAccount', registerFioDomainAddress = 'registerFioDomainAddress', registerFioAddress = 'registerFioAddress', registerOwnerFioAddress = 'registerOwnerFioAddress', transferLockedTokens = 'transferLockedTokens', registerFioDomain = 'registerFioDomain', registerOwnerFioDomain = 'registerOwnerFioDomain', renewFioDomain = 'renewFioDomain', renewFioAddress = 'renewFioAddress', burnFioAddress = 'burnFioAddress', transferFioAddress = 'transferFioAddress', transferFioDomain = 'transferFioDomain', addBundledTransactions = 'addBundledTransactions', addPublicAddress = 'addPublicAddress', addPublicAddresses = 'addPublicAddresses', removePublicAddresses = 'removePublicAddresses', getLocks = 'getLocks', cancelFundsRequest = 'cancelFundsRequest', removeAllPublicAddresses = 'removeAllPublicAddresses', setFioDomainVisibility = 'setFioDomainVisibility', recordObtData = 'recordObtData', getObtData = 'getObtData', getGranteePermissions = 'getGranteePermissions', getGrantorPermissions = 'getGrantorPermissions', getObjectPermissions = 'getObjectPermissions', rejectFundsRequest = 'rejectFundsRequest', requestFunds = 'requestFunds', isAvailable = 'isAvailable', getFioBalance = 'getFioBalance', getFioNames = 'getFioNames', getFioDomains = 'getFioDomains', getFioAddresses = 'getFioAddresses', getPendingFioRequests = 'getPendingFioRequests', getReceivedFioRequests = 'getReceivedFioRequests', getCancelledFioRequests = 'getCancelledFioRequests', getSentFioRequests = 'getSentFioRequests', getPublicAddress = 'getPublicAddress', getFioPublicAddress = 'getFioPublicAddress', getPublicAddresses = 'getPublicAddresses', getNfts = 'getNfts', transferTokens = 'transferTokens', stakeFioTokens = 'stakeFioTokens', unStakeFioTokens = 'unStakeFioTokens', getOracleFees = 'getOracleFees', getAbi = 'getAbi', getFee = 'getFee', getFeeForRecordObtData = 'getFeeForRecordObtData', getFeeForNewFundsRequest = 'getFeeForNewFundsRequest', getFeeForRejectFundsRequest = 'getFeeForRejectFundsRequest', getFeeForBurnFioAddress = 'getFeeForBurnFioAddress', getFeeForTransferFioAddress = 'getFeeForTransferFioAddress', getFeeForTransferFioDomain = 'getFeeForTransferFioDomain', getFeeForAddBundledTransactions = 'getFeeForAddBundledTransactions', getFeeForAddPublicAddress = 'getFeeForAddPublicAddress', getFeeForCancelFundsRequest = 'getFeeForCancelFundsRequest', getFeeForRemovePublicAddresses = 'getFeeForRemovePublicAddresses', getFeeForRemoveAllPublicAddresses = 'getFeeForRemoveAllPublicAddresses', getFeeForTransferLockedTokens = 'getFeeForTransferLockedTokens', getMultiplier = 'getMultiplier', pushTransaction = 'pushTransaction', getAccountPubKey = 'getAccountPubKey', getEncryptKey = 'getEncryptKey', } type GenericActions = { [GenericAction.getFioPublicKey]: { options: [] response: string, } [GenericAction.getAccount]: { options: [GetAccountOptions] response: Promise<AccountResponse>, } [GenericAction.registerFioDomainAddress]: { options: [RegisterFioDomainAddressOptions] response: Promise<RegisterFioAddressResponse>, } [GenericAction.registerFioAddress]: { options: [Omit<RegisterOwnerFioAddressOptions, 'ownerPublicKey'> & Partial<Pick<RegisterOwnerFioAddressOptions, 'ownerPublicKey'>>] response: Promise<RegisterFioAddressResponse>, } [GenericAction.registerOwnerFioAddress]: { options: [RegisterOwnerFioAddressOptions] response: Promise<RegisterFioAddressResponse>, } [GenericAction.transferLockedTokens]: { options: [TransferLockedTokensOptions] response: Promise<TransferLockedTokensResponse>, } [GenericAction.registerFioDomain]: { options: [RegisterFioDomainOptions] response: Promise<RegisterFioDomainResponse>, } [GenericAction.registerOwnerFioDomain]: { options: [RegisterOwnerFioDomainOptions] response: Promise<RegisterFioDomainResponse>, } [GenericAction.renewFioDomain]: { options: [RenewFioDomainOptions] response: Promise<RenewFioDomainResponse>, } [GenericAction.renewFioAddress]: { options: [RenewFioAddressOptions] response: Promise<RenewFioAddressResponse>, } [GenericAction.burnFioAddress]: { options: [BurnFioAddressOptions] response: Promise<BurnFioAddressResponse>, } [GenericAction.transferFioAddress]: { options: [TransferFioAddressOptions] response: Promise<TransferFioAddressResponse>, } [GenericAction.transferFioDomain]: { options: [TransferFioDomainOptions] response: Promise<TransferFioDomainResponse>, } [GenericAction.addBundledTransactions]: { options: [AddBundledTransactionsOptions] response: Promise<AddBundledTransactionsResponse>, } [GenericAction.addPublicAddress]: { options: [AddPublicAddressOptions] response: Promise<AddPublicAddressesResponse>, } [GenericAction.addPublicAddresses]: { options: [AddPublicAddressesOptions] response: Promise<AddPublicAddressesResponse>, } [GenericAction.removePublicAddresses]: { options: [RemovePublicAddressesOptions] response: Promise<RemovePublicAddressesResponse>, } [GenericAction.getLocks]: { options: [GetLocksOptions] response: Promise<LocksResponse>, } [GenericAction.cancelFundsRequest]: { options: [CancelFundsRequestOptions] response: Promise<CancelFundsRequestResponse>, } [GenericAction.removeAllPublicAddresses]: { options: [RemoveAllPublicAddressesOptions] response: Promise<RemoveAllPublicAddressesResponse>, } [GenericAction.setFioDomainVisibility]: { options: [SetFioDomainVisibilityOptions] response: Promise<SetFioDomainVisibilityResponse>, } [GenericAction.recordObtData]: { options: [RecordObtDataOptions] response: Promise<RecordObtDataResponse>, } [GenericAction.getObtData]: { options: [GetObtDataOptions] response: Promise<GetObtDataDecryptedResponse>, } [GenericAction.getGranteePermissions]: { options: [GetGranteePermissionsOptions] response: Promise<PermissionsResponse>, } [GenericAction.getGrantorPermissions]: { options: [GetGrantorPermissionsOptions] response: Promise<PermissionsResponse>, } [GenericAction.getObjectPermissions]: { options: [GetObjectPermissionsOptions] response: Promise<PermissionsResponse>, } [GenericAction.rejectFundsRequest]: { options: [RejectFundsRequestOptions] response: Promise<RejectFundsResponse>, } [GenericAction.requestFunds]: { options: [RequestFundsOptions] response: Promise<RequestFundsResponse>, } [GenericAction.isAvailable]: { options: [IsAvailableOptions] response: Promise<AvailabilityResponse>, } [GenericAction.getFioBalance]: { options: [GetFioBalanceOptions] response: Promise<BalanceResponse>, } [GenericAction.getFioNames]: { options: [GetFioNamesOptions] response: Promise<FioNamesResponse>, } [GenericAction.getFioDomains]: { options: [GetFioDomainsOptions] response: Promise<FioDomainsResponse>, } [GenericAction.getFioAddresses]: { options: [GetFioAddressesOptions] response: Promise<FioAddressesResponse>, } [GenericAction.getPendingFioRequests]: { options: [GetPendingFioRequestsOptions] response: Promise<PendingFioRequestsDecryptedResponse>, } [GenericAction.getReceivedFioRequests]: { options: [GetReceivedFioRequestsOptions] response: Promise<ReceivedFioRequestsDecryptedResponse>, } [GenericAction.getCancelledFioRequests]: { options: [GetCancelledFioRequestsOptions] response: Promise<CancelledFioRequestsDecryptedResponse>, } [GenericAction.getSentFioRequests]: { options: [GetSentFioRequestsOptions] response: Promise<SentFioRequestsDecryptedResponse>, } [GenericAction.getPublicAddress]: { options: [GetPublicAddressOptions] response: Promise<PublicAddressResponse>, } [GenericAction.getFioPublicAddress]: { options: [GetFioPublicAddressOptions] response: Promise<PublicAddressResponse>, } [GenericAction.getPublicAddresses]: { options: [GetPublicAddressesOptions] response: Promise<PublicAddressesResponse>, } [GenericAction.getNfts]: { options: [GetNftsOptions] response: Promise<NftsResponse>, } [GenericAction.transferTokens]: { options: [TransferTokensOptions] response: Promise<TransferTokensResponse>, } [GenericAction.stakeFioTokens]: { options: [StakeFioTokensOptions] response: Promise<TransactionResponse>, } [GenericAction.unStakeFioTokens]: { options: [UnStakeFioTokensOptions] response: Promise<TransactionResponse>, } [GenericAction.getOracleFees]: { options: [GetOracleFeesOptions] response: Promise<FioOracleFeesResponse>, } [GenericAction.getFee]: { options: [GetFeeOptions] response: Promise<FioFeeResponse>, } [GenericAction.getAbi]: { options: [GetAbiOptions] response: Promise<AbiResponse>, } [GenericAction.getFeeForRecordObtData]: { options: [GetFeeForRecordObtDataOptions] response: Promise<FioFeeResponse>, } [GenericAction.getFeeForNewFundsRequest]: { options: [GetFeeForNewFundsRequestOptions] response: Promise<FioFeeResponse>, } [GenericAction.getFeeForRejectFundsRequest]: { options: [GetFeeForRejectFundsRequestOptions] response: Promise<FioFeeResponse>, } [GenericAction.getFeeForBurnFioAddress]: { options: [GetFeeForBurnFioAddressOptions] response: Promise<FioFeeResponse>, } [GenericAction.getFeeForTransferFioAddress]: { options: [GetFeeForTransferFioAddressOptions] response: Promise<FioFeeResponse>, } [GenericAction.getFeeForTransferFioDomain]: { options: [GetFeeForTransferFioDomainOptions] response: Promise<FioFeeResponse>, } [GenericAction.getFeeForAddBundledTransactions]: { options: [GetFeeForAddBundledTransactionsOptions] response: Promise<FioFeeResponse>, } [GenericAction.getFeeForAddPublicAddress]: { options: [GetFeeForAddPublicAddressOptions] response: Promise<FioFeeResponse>, } [GenericAction.getFeeForCancelFundsRequest]: { options: [GetFeeForCancelFundsRequestOptions] response: Promise<FioFeeResponse>, } [GenericAction.getFeeForRemovePublicAddresses]: { options: [GetFeeForRemovePublicAddressesOptions] response: Promise<FioFeeResponse>, } [GenericAction.getFeeForRemoveAllPublicAddresses]: { options: [GetFeeForRemoveAllPublicAddressesOptions] response: Promise<FioFeeResponse>, } [GenericAction.getFeeForTransferLockedTokens]: { options: [GetFeeForTransferLockedTokensOptions] response: Promise<FioFeeResponse>, } [GenericAction.getMultiplier]: { options: [] response: number, } [GenericAction.pushTransaction]: { options: [PushTransactionOptions] response: Promise<unknown>, } [GenericAction.getAccountPubKey]: { options: [GetAccountPubKeyOptions] response: Promise<GetAccountPubKeyResponse>, } [GenericAction.getEncryptKey]: { options: [GetEncryptKeyOptions] response: Promise<GetEncryptKeyResponse>, }, } export class FIOSDK { /** * @ignore * Needed for testing abi */ public static customRawAbiAccountName: string[] | null /** * SUFs = Smallest Units of FIO */ public static SUFUnit: number = 1000000000 public static rawAbiMissingWarnings: string[] /** * @ignore * Needed for testing abi */ public static setCustomRawAbiAccountName(customRawAbiAccountName: string | null) { if (customRawAbiAccountName) { FIOSDK.customRawAbiAccountName = [customRawAbiAccountName] } else { FIOSDK.customRawAbiAccountName = null } } /** * Private key generation in the SDK is available for testing purposes only. * Do not generate private keys for production application using this method. * Instead pass securely generated private keys or seed phrase to the SDK constructor. * * @ignore */ public static async createPrivateKey(entropy: Buffer): Promise<{ fioKey: string; mnemonic: string; }> { const bip39 = require('bip39') const mnemonic = bip39.entropyToMnemonic(entropy) return await FIOSDK.createPrivateKeyMnemonic(mnemonic) } /** * Create a FIO private key. * * Private key generation in the SDK is available for testing purposes only. * Do not generate private keys for production application using this method. * Instead pass securely generated private keys or seed phrase to the SDK constructor. * * @param mnemonic mnemonic used to generate a random unique private key. * @example real flame win provide layer trigger soda erode upset rate beef wrist fame design merit * * @returns New FIO private key */ public static async createPrivateKeyMnemonic(mnemonic: string) { const hdkey = require('hdkey') const wif = require('wif') const bip39 = require('bip39') const seedBytes = await bip39.mnemonicToSeed(mnemonic) const seed = await seedBytes.toString('hex') const master = hdkey.fromMasterSeed(new Buffer(seed, 'hex')) const node = master.derive('m/44\'/235\'/0\'/0/0') const fioKey = wif.encode(128, node._privateKey, false) return {fioKey, mnemonic} } /** * Create a FIO public key. * * @param fioPrivateKey FIO private key. * * @returns FIO public key derived from the FIO private key. */ public static derivedPublicKey(fioPrivateKey: string) { const publicKey: string = Ecc.privateToPublic(fioPrivateKey) return {publicKey} } /** * hash a pub key * * @param fioPublicKey FIO private key. * * @returns FIO account derived from pub key. */ public static accountHash(fioPublicKey: string) { const accountnm = Fio.accountHash(fioPublicKey) return {accountnm} } /** * @deprecated use {@link FIOSDK#validateChainCode} * Is the Chain Code Valid? * * @param chainCode * * @returns Chain Code is Valid */ public static isChainCodeValid(chainCode: string) { const validation = validate({chainCode}, {chainCode: allRules.chain}) if (!validation.isValid) { throw new ValidationError(validation.errors, `Validation error`) } return validation.isValid } /** * @deprecated use {@link FIOSDK#validateTokenCode} * Is the Token Code Valid? * * @param tokenCode * * @returns Token Code is Valid */ public static isTokenCodeValid(tokenCode: string) { const validation = validate({tokenCode}, {tokenCode: allRules.chain}) if (!validation.isValid) { throw new ValidationError(validation.errors) } return validation.isValid } /** * @deprecated use {@link FIOSDK#validateFioAddress} * Is the FIO Address Valid? * * @param fioAddress * * @returns Fio Address is Valid */ public static isFioAddressValid(fioAddress: string) { const validation = validate({fioAddress}, {fioAddress: allRules.fioAddress}) if (!validation.isValid) { throw new ValidationError(validation.errors) } return validation.isValid } /** * @deprecated use {@link FIOSDK#validateFioDomain} * Is the FIO Domain Valid? * * @param fioDomain * * @returns FIO Domain is Valid */ public static isFioDomainValid(fioDomain: string) { const validation = validate({fioDomain}, {fioDomain: allRules.fioDomain}) if (!validation.isValid) { throw new ValidationError(validation.errors) } return validation.isValid } /** * @deprecated use {@link FIOSDK#validateFioPublicKey} * Is the FIO Public Key Valid? * * @param fioPublicKey * * @returns FIO Public Key is Valid */ public static isFioPublicKeyValid(fioPublicKey: string) { const validation = validate({fioPublicKey}, {fioPublicKey: allRules.fioPublicKey}) if (!validation.isValid) { throw new ValidationError(validation.errors) } return validation.isValid } /** * @deprecated use {@link FIOSDK#validatePublicAddress} * Is the Public Address Valid? * * @param publicAddress * * @returns Public Address is Valid */ public static isPublicAddressValid(publicAddress: string) { const validation = validate({publicAddress}, {publicAddress: allRules.nativeBlockchainPublicAddress}) if (!validation.isValid) { throw new ValidationError(validation.errors) } return validation.isValid } /** * Convert a FIO Token Amount to FIO SUFs * * @param amount * * 2.568 FIO should be 2568000000 SUFs * * @returns FIO SUFs */ public static amountToSUF(amount: number): number { // get integer part const floor = Math.floor(amount) const tempResult = floor * this.SUFUnit // get remainder const remainder: number = Number((amount % 1).toFixed(9)) const remainderResult = remainder * (this.SUFUnit) const floorRemainder = Math.floor(remainderResult) // add integer and remainder return tempResult + floorRemainder } /** * Convert FIO SUFs to a FIO Token amount * * @param suf {string | number} * * @returns FIO Token amount */ public static SUFToAmount(suf: number | string): number { return (typeof suf === 'number' ? suf : parseInt(suf, 10)) / this.SUFUnit } /** * Convert a FIO Token Amount to FIO SUFs * * @param amount * * 2.568 FIO should be 2568000000 SUFs * * @returns {string} FIO SUFs */ public static amountToSUFString(amount: number | string): string { const floor = new Big(amount).round(0, 0).toString(); const tempResult = new Big(floor).mul(this.SUFUnit).toString(); // get remainder const remainder = new Big(amount) .mod(1) .round(9, 2) .toString(); const remainderResult = new Big(remainder).mul(this.SUFUnit).toString(); const floorRemainder = new Big(remainderResult).round(0, 0).toString(); // add integer and remainder return new Big(tempResult).add(floorRemainder).toString(); } /** * Convert FIO SUFs to a FIO Token amount * * @param suf {string | number} * * @returns {string} FIO Token amount */ public static SUFToAmountString(suf: number | string): string { return new Big(suf).div(this.SUFUnit).toString(); } /** * Set stored raw abi missing warnings */ public static setRawAbiMissingWarnings(rawAbiName: string, fioSdkInstance: FIOSDK) { fioSdkInstance.rawAbiMissingWarnings.push(rawAbiName) } public config: RequestConfig public static get abiMap() { return Transactions.abiMap } public get transactions() { const request = new Transactions(this.config) return { createRawTransaction: request.createRawTransaction.bind(request), getActor: request.getActor.bind(request), getBlock: request.getBlock.bind(request), getChainDataForTx: request.getChainDataForTx.bind(request), getChainInfo: request.getChainInfo.bind(request), getCipherContent, getUnCipherContent, serialize: request.serialize.bind(request), deserialize: request.deserialize.bind(request), } } /** * @ignore */ public registerMockUrl: string /** * the fio private key of the client sending requests to FIO API. */ public privateKey: string /** * the fio public key of the client sending requests to FIO API. */ public publicKey: string /** * Default FIO Address of the wallet which generates transactions. */ public technologyProviderId: string /** * Stored raw abi missing warnings */ public rawAbiMissingWarnings: string[] /** * @ignore */ private proxyHandle = { // We save reference to our class inside the object main: this, /** * To apply will be fired each time the function is called * @param target Called function * @param scope Scope from where function was called * @param args Arguments passed to function * @return Results of the function */ async apply(target: any, scope: any, args: any) { // Remember that you have to exclude methods which you are going to use // inside here to avoid “too much recursion” error const setAbi = async (accountName: string): Promise<void> => { if (!Transactions.abiMap.get(accountName)) { const newAbi = await this.main.getAbi({accountName}) if (newAbi && newAbi.account_name) { Transactions.abiMap.set(newAbi.account_name, newAbi) } } } let rawAbiAccountNameList = [] if (FIOSDK.customRawAbiAccountName) { rawAbiAccountNameList = [...Object.values(Account), ...FIOSDK.customRawAbiAccountName] } else { rawAbiAccountNameList = Object.values(Account) } const setAbiPromises = rawAbiAccountNameList.map((accountName) => setAbi(accountName)) await Promise.allSettled(setAbiPromises).then((results) => results.forEach((result) => { if (result.status === 'rejected') { let error = '' const reason = result.reason const errorObj = reason.json || reason.errors && reason.errors[0].json if (errorObj) { error = errorObj.error?.details[0]?.message } if (!error) { error = reason.message } if (error.includes(fioConstants.missingAbiError)) { const abiAccountName = reason.requestParams && reason.requestParams.body && reason.requestParams.body .replace('{', '') .replace('}', '') .split(':')[1] .replace('\"', '') .replace('\"', '') if (!this.main.rawAbiMissingWarnings?.includes(abiAccountName) || (FIOSDK.customRawAbiAccountName && FIOSDK.customRawAbiAccountName.includes(abiAccountName)) ) { // tslint:disable-next-line:no-console console.warn('\x1b[33m', 'FIO_SDK ABI WARNING:', error) FIOSDK.setRawAbiMissingWarnings(abiAccountName, this.main) } } else { throw new Error(`FIO_SDK ABI Error: ${result.reason}`) } } })) // Here we bind method with our class by accessing reference to instance return target.bind(this.main)(...args) }, } /** * @ignore * Defines whether SignedTransaction would execute or return prepared transaction */ private returnPreparedTrx: boolean /** * @deprecated * * @param privateKey the fio private key of the client sending requests to FIO API. * @param publicKey the fio public key of the client sending requests to FIO API. * @param apiUrls the url or list of urls to the FIO API. * @param fetchJson - the module to use for HTTP Post/Get calls * How to instantiate fetchJson parameter: * ```ts * // i.e. * fetch = require('node-fetch') * * const fetchJson = async (uri, opts = {}) => { * return fetch(uri, opts) * } * ``` * @param registerMockUrl the url to the mock server * @param technologyProviderId Default FIO Address of the wallet which generates transactions. * @param returnPreparedTrx flag indicate that it should return prepared transaction or should be pushed to server. * @param logger {@link FioLogger} FIO logger to handle all requests. */ constructor( privateKey: string, publicKey: string, apiUrls: string[] | string, fetchJson: FetchJson, registerMockUrl?: string | null, technologyProviderId?: string | null, returnPreparedTrx?: boolean | null, logger?: FioLogger | null, ) /** * @param options.privateKey the fio private key of the client sending requests to FIO API. * @param options.publicKey the fio public key of the client sending requests to FIO API. * @param options.apiUrls the url or list of urls to the FIO API. * @param options.fetchJson - the module to use for HTTP Post/Get calls * How to instantiate fetchJson parameter i.e.: * fetch = require('node-fetch') * * const fetchJson = async (uri, opts = {}) => { * return fetch(uri, opts) * } * @param options.registerMockUrl the url to the mock server * @param options.technologyProviderId Default FIO Address of the wallet which generates transactions. * @param options.returnPreparedTrx flag indicate that it should return prepared transaction * or should be pushed to server. * @param options.logger FIO logger to handle all requests. */ constructor(options: FioSdkOptions) constructor() { const { privateKey = '', publicKey = '', apiUrls, fetchJson, registerMockUrl = '', technologyProviderId = '', returnPreparedTrx = false, logger, } = resolveOptions<FioSdkOptions>({ arguments: Array.from(arguments), keys: ['privateKey', 'publicKey', 'apiUrls', 'fetchJson', 'registerMockUrl', 'technologyProviderId', 'returnPreparedTrx', 'throwValidationErrors', 'logger'], }) this.config = { baseUrls: Array.isArray(apiUrls) ? apiUrls : [apiUrls], fetchJson, fioProvider: Fio, logger, } this.registerMockUrl = registerMockUrl this.privateKey = privateKey this.publicKey = publicKey this.technologyProviderId = technologyProviderId this.returnPreparedTrx = returnPreparedTrx this.rawAbiMissingWarnings = [] const methods = Object.getOwnPropertyNames(FIOSDK.prototype).filter( (name) => !fioConstants.classMethodsToExcludeFromProxy.includes(name as ClassMethodsToExcludeFromProxy), ) // Replace all methods with Proxy methods // Find and remove constructor as we don't need Proxy on it methods.forEach((methodName) => { this[methodName as keyof Omit<FIOSDK, ClassMethodsToExcludeFromProxy>] = new Proxy( this[methodName as keyof FIOSDK], this.proxyHandle, ) }) } /** * Is the Chain Code Valid? * * @param chainCode * * @returns Chain Code is Valid */ public validateChainCode(chainCode: string) { const validation = validate({chainCode}, {chainCode: allRules.chain}) if (!validation.isValid) { this.config.logger?.({ context: { errors: validation.errors, name: 'validateChainCode', }, type: 'validation', }) } return validation.isValid } /** * Is the Token Code Valid? * * @param tokenCode * * @returns Token Code is Valid */ public validateTokenCode(tokenCode: string) { const validation = validate({tokenCode}, {tokenCode: allRules.chain}) if (!validation.isValid) { this.config.logger?.({ context: { errors: validation.errors, name: 'validateTokenCode', }, type: 'validation', }) } return validation.isValid } /** * Is the FIO Address Valid? * * @param fioAddress * * @returns Fio Address is Valid */ public validateFioAddress(fioAddress: string) { const validation = validate({fioAddress}, {fioAddress: allRules.fioAddress}) if (!validation.isValid) { this.config.logger?.({ context: { errors: validation.errors, name: 'validateFioAddress', }, type: 'validation', }) } return validation.isValid } /** * Is the FIO Domain Valid? * * @param fioDomain * * @returns FIO Domain is Valid */ public validateFioDomain(fioDomain: string) { const validation = validate({fioDomain}, {fioDomain: allRules.fioDomain}) if (!validation.isValid) { this.config.logger?.({ context: { errors: validation.errors, name: 'validateFioDomain', }, type: 'validation', }) } return validation.isValid } /** * Is the FIO Public Key Valid? * * @param fioPublicKey * * @returns FIO Public Key is Valid */ public validateFioPublicKey(fioPublicKey: string) { const validation = validate({fioPublicKey}, {fioPublicKey: allRules.fioPublicKey}) if (!validation.isValid) { this.config.logger?.({ context: { errors: validation.errors, name: 'validateFioPublicKey', }, type: 'validation', }) } return validation.isValid } /** * Is the Public Address Valid? * * @param publicAddress * * @returns Public Address is Valid */ public validatePublicAddress(publicAddress: string) { const validation = validate({publicAddress}, {publicAddress: allRules.nativeBlockchainPublicAddress}) if (!validation.isValid) { this.config.logger?.({ context: { errors: validation.errors, name: 'validatePublicAddress', }, type: 'validation', }) } return validation.isValid } /** * Retrieves the FIO public key assigned to the FIOSDK instance. */ public getFioPublicKey(): string { return this.publicKey } /** * Returns technologyProviderId or default */ public getTechnologyProviderId(technologyProviderId?: string | null): string { return technologyProviderId !== undefined && technologyProviderId !== null ? technologyProviderId : this.technologyProviderId } /** * Set returnPreparedTrx */ public setSignedTrxReturnOption(returnPreparedTrx: boolean): void { this.returnPreparedTrx = returnPreparedTrx } /** * Set transactions baseUrls */ public setApiUrls(apiUrls: string[]): void { this.config.baseUrls = apiUrls } /** * Execute prepared transaction. * * @param endPoint endpoint. * @param preparedTrx */ public async executePreparedTrx( endPoint: EndPoint, preparedTrx: unknown, ): Promise<any> { const response = await new Transactions(this.config).multicastServers({ body: JSON.stringify(preparedTrx), endpoint: `chain/${endPoint}`, }) return SignedTransaction.prepareResponse(response, true) } /** * @deprecated * Registers a FIO Address on the FIO blockchain. * The owner will be the public key associated with the FIO SDK instance. * * @param fioAddress FIO Address to register. * @param maxFee Maximum amount of SUFs the user is willing to pay for fee. * Should be preceded by @ [getFee] for correct value. * @param technologyProviderId FIO Address of the wallet which generates this transaction. * @param expirationOffset Expiration time offset for this transaction in seconds. * Default is 180 seconds. Increasing number of seconds gives transaction more lifetime term. */ public registerFioAddress( fioAddress: string, maxFee: number, technologyProviderId?: string | null, expirationOffset?: number | null, ): Promise<RegisterFioAddressResponse> /** * Registers a FIO Address on the FIO blockchain. * The owner will be the public key associated with the FIO SDK instance. * * @param options.fioAddress FIO Address to register. * @param options.maxFee Maximum amount of SUFs the user is willing to pay for fee. * Should be preceded by @ [getFee] for correct value. * @param options.technologyProviderId FIO Address of the wallet which generates this transaction. * @param options.expirationOffset Expiration time offset for this transaction in seconds. * Default is 180 seconds. Increasing number of seconds gives transaction more lifetime term. */ public registerFioAddress(options: RegisterFioAddressOptions): Promise<RegisterFioAddressResponse> public registerFioAddress(): Promise<RegisterFioAddressResponse> { const args = resolveOptions<RegisterFioAddressOptions>({ arguments: Array.from(arguments), keys: ['fioAddress', 'maxFee', 'technologyProviderId', 'expirationOffset'], }) const registerFioAddress = new requests.RegisterFioAddress(this.config, { ...args, technologyProviderId: this.getTechnologyProviderId(args.technologyProviderId), }) return registerFioAddress.execute( this.privateKey, this.publicKey, this.returnPreparedTrx, args.expirationOffset, ) } /** * @deprecated * Registers a Fio Address on behalf of the owner FIO Public key parameter. * Owner FIO Public key owns the FIO address * * @param fioAddress FIO Address to register. * @param ownerPublicKey Owner FIO Public Key. * @param maxFee Maximum amount of SUFs the user is willing to pay for fee. Should be preceded * by @ [getFee] for correct value. * @param technologyProviderId FIO Address of the wallet which generates this transaction. * @param expirationOffset Expiration time offset for this transaction in seconds. Default is 180 seconds. * Increasing number of seconds gives transaction more lifetime term. */ public registerOwnerFioAddress( fioAddress: string, ownerPublicKey: string, maxFee: number, technologyProviderId?: string | null, expirationOffset?: number | null, ): Promise<RegisterFioAddressResponse> /** * Registers a Fio Address on behalf of the owner FIO Public key parameter. * Owner FIO Public key owns the FIO address * * @param options.fioAddress FIO Address to register. * @param options.ownerPublicKey Owner FIO Public Key. * @param options.maxFee Maximum amount of SUFs the user is willing to pay for fee. Should be preceded * by @ [getFee] for correct value. * @param options.technologyProviderId FIO Address of the wallet which generates this transaction. * @param options.expirationOffset Expiration time offset for this transaction in seconds. Default is 180 seconds. * Increasing number of seconds gives transaction more lifetime term. */ public registerOwnerFioAddress(options: RegisterOwnerFioAddressOptions): Promise<RegisterFioAddressResponse> public registerOwnerFioAddress(): Promise<RegisterFioAddressResponse> { const args = resolveOptions<RegisterOwnerFioAddressOptions>({ arguments: Array.from(arguments), keys: ['fioAddress', 'ownerPublicKey', 'maxFee', 'technologyProviderId', 'expirationOffset'], }) const registerFioAddress = new requests.RegisterFioAddress( this.config, { ...args, technologyProviderId: this.getTechnologyProviderId(args.technologyProviderId), }, ) return registerFioAddress.execute( this.privateKey, this.publicKey, this.returnPreparedTrx, args.expirationOffset, ) } /** * Registers a FIO Address and FIO domain on behalf of the owner FIO Public key parameter. * Owner FIO Public key owns the FIO address * * @param options.fioAddress FIO Address to register. * @param options.isPublic true - allows anyone to register FIO Address, * false - only owner of domain can register FIO Address. * @param options.ownerPublicKey Owner FIO Public Key. * @param options.maxFee Maximum amount of SUFs the user is willing to pay for fee. * Should be preceded by @ [getFee] for correct value. * @param options.technologyProviderId FIO Address of the wallet which generates this transaction. * @param options.expirationOffset Expiration time offset for this transaction in seconds. * Default is 180 seconds. Increasing number of seconds gives transaction more lifetime term. */ public registerFioDomainAddress(options: RegisterFioDomainAddressOptions): Promise<RegisterFioAddressResponse> { const args = cleanupObject(options) const registerFioDomainAddress = new requests.RegisterFioDomainAddress( this.config, { ...args, technologyProviderId: this.getTechnologyProviderId(args.technologyProviderId), }, ) return registerFioDomainAddress.execute( this.privateKey, this.publicKey, this.returnPreparedTrx, args.expirationOffset, ) } /** * @deprecated * Registers a FIO Domain on the FIO blockchain. * * @param fioDomain FIO Domain to register. The owner will be the public key associated with the FIO SDK instance. * @param maxFee Maximum amount of SUFs the user is willing to pay for fee. * Should be preceded by @ [getFee] for correct value. * @param technologyProviderId FIO Address of the wallet which generates this transaction. * @param expirationOffset Expiration time offset for this transaction in seconds. * Default is 180 seconds. Increasing number of seconds gives transaction more lifetime term. */ public registerFioDomain( fioDomain: string, maxFee: number, technologyProviderId?: string | null, expirationOffset?: number | null, ): Promise<RegisterFioDomainResponse> /** * Registers a FIO Domain on the FIO blockchain. * * @param options.fioDomain FIO Domain to register. The owner will be the public key associated * with the FIO SDK instance. * @param options.maxFee Maximum amount of SUFs the user is willing to pay for fee. * Should be preceded by @ [getFee] for correct value. * @param options.ownerPublicKey Owner FIO Public Key. * @param options.technologyProviderId FIO Address of the wallet which generates this transaction. * @param options.expirationOffset Expiration time offset for this transaction in seconds. * Default is 180 seconds. Increasing number of seconds gives transaction more lifetime term. */ public registerFioDomain(options: RegisterFioDomainOptions): Promise<RegisterFioDomainResponse> public registerFioDomain(): Promise<RegisterFioDomainResponse> { const args = resolveOptions<RegisterFioDomainOptions>({ arguments: Array.from(arguments), keys: ['fioDomain', 'maxFee', 'technologyProviderId', 'expirationOffset'], }) const registerFioDomain = new requests.RegisterFioDomain( this.config, { ...args, technologyProviderId: this.getTechnologyProviderId(args.technologyProviderId), }, ) return registerFioDomain.execute(this.privateKey, this.publicKey, this.returnPreparedTrx, args.expirationOffset) } /** * @deprecated * Registers a FIO Domain on behalf of the owner FIO Public key parameter. Owner FIO Public key owns the FIO domain. * * @param fioDomain FIO Domain to register. The owner will be the public key associated with the FIO SDK instance. * @param ownerPublicKey Owner FIO Public Key. * @param maxFee Maximum amount of SUFs the user is willing to pay for fee. * Should be preceded by @ [getFee] for correct value. * @param technologyProviderId FIO Address of the wallet which generates this transaction. * @param expirationOffset Expiration time offset for this transaction in seconds. * Default is 180 seconds. Increasing number of seconds gives transaction more lifetime term. */ public registerOwnerFioDomain( fioDomain: string, ownerPublicKey: string, maxFee: number, technologyProviderId?: string | null, expirationOffset?: number | null, ): Promise<RegisterFioDomainResponse> /** * Registers a FIO Domain on behalf of the owner FIO Public key parameter. Owner FIO Public key owns the FIO domain. * * @param options.fioDomain FIO Domain to register. The owner will be the public key associated * with the FIO SDK instance. * @param options.ownerPublicKey Owner FIO Public Key. * @param options.maxFee Maximum amount of SUFs the user is willing to pay for fee. * Should be preceded by @ [getFee] for correct value. * @param options.technologyProviderId FIO Address of the wallet which generates this transaction. * @param options.expirationOffset Expiration time offset for this transaction in seconds. * Default is 180 seconds. Increasing number of seconds gives transaction more lifetime term. */ public registerOwnerFioDomain(options: RegisterOwnerFioDomainOptions): Promise<RegisterFioDomainResponse> public registerOwnerFioDomain(): Promise<RegisterFioDomainResponse> { const args = resolveOptions<RegisterOwnerFioDomainOptions>({ arguments: Array.from(arguments), keys: ['fioDomain', 'ownerPublicKey', 'maxFee', 'technologyProviderId', 'expirationOffset'], }) const registerFioDomain = new requests.RegisterFioDomain(this.config, { ...args, technologyProviderId: this.getTechnologyProviderId(args.technologyProviderId), }, ) return registerFioDomain.execute(this.privateKey, this.publicKey, this.returnPreparedTrx, args.expirationOffset) } /** * @deprecated * Burns a FIO Address on the FIO blockchain. * * @param fioAddress FIO Address to burn. The owner will be the public key associated with the FIO SDK instance. * @param maxFee Maximum amount of SUFs the user is willing to pay for fee. * Should be preceded by @ [getFee] for correct value. * @param technologyProviderId FIO Address of the wallet which generates this transaction. */ public burnFioAddress( fioAddress: string, maxFee: number, technologyProviderId?: string | null, ): Promise<BurnFioAddressResponse> /** * Burns a FIO Address on the FIO blockchain. * * @param options.fioAddress FIO Address to burn. The owner will be the public key associated * with the FIO SDK instance. * @param options.maxFee Maximum amount of SUFs the user is willing to pay for fee. * Should be preceded by @ [getFee] for correct value. * @param options.technologyProviderId FIO Address of the wallet which generates this transaction. */ public burnFioAddress(options: BurnFioAddressOptions): Promise<BurnFioAddressResponse> public burnFioAddress(): Promise<BurnFioAddressResponse> { const args = resolveOptions<BurnFioAddressOptions>({ arguments: Array.from(arguments), keys: ['fioAddress', 'maxFee', 'technologyProviderId'], }) const burnFioAddress = new requests.BurnFioAddress( this.config, { ...ar