/* eslint-disable */ import fetch from 'cross-fetch'; import { Balance } from './interfaces/Balance'; import { Platform } from './interfaces/Platform'; import { Organization } from './interfaces/Organization'; import { Nexus } from './interfaces/Nexus'; import { Account } from './interfaces/Account'; import { Leaderboard } from './interfaces/Leaderboard'; import { Chain } from './interfaces/Chain'; import { Contract } from './interfaces/Contract'; import { Event } from './interfaces/Event'; import { TransactionData } from './interfaces/TransactionData'; import { AccountTransactions } from './interfaces/AccountTransactions'; import { Paginated } from './interfaces/Paginated'; import { Block } from './interfaces/Block'; import { Token } from './interfaces/Token'; import { TokenData } from './interfaces/TokenData'; import { Auction } from './interfaces/Auction'; import { Script } from './interfaces/Script'; import { Archive } from './interfaces/Archive'; import { ABIContract } from './interfaces/ABIContract'; import { Receipt } from './interfaces/Receipt'; import { Peer } from './interfaces/Peer'; import { Validator } from './interfaces/Validator'; import { Swap } from './interfaces/Swap'; import { NFT } from './interfaces/NFT'; export class PhantasmaAPI { host: string; rpcName: string; nexus: string; availableHosts: any[]; pingAsync(host: string): Promise { return new Promise((resolve, reject) => { var started = new Date().getTime(); var http = new XMLHttpRequest(); http.open('GET', host + '/rpc', true); http.timeout = 4500; http.onreadystatechange = function () { if (http.readyState == 4 && http.status == 200) { var ended = new Date().getTime(); var milliseconds = ended - started; resolve(milliseconds); } http.ontimeout = function () { resolve(100000); }; http.onerror = function () { resolve(100000); }; }; try { http.send(null); } catch (exception) { // this is expected reject(); } }); } constructor(defHost: string, peersUrlJson: string, nexus: string) { this.rpcName = 'Auto'; this.nexus = nexus; this.host = defHost; this.availableHosts = []; if (peersUrlJson != undefined) { fetch(peersUrlJson + '?_=' + new Date().getTime()).then(async (res) => { const data = await res.json(); for (var i = 0; i < data.length; i++) { console.log('Checking RPC: ', data[i]); try { const msecs = await this.pingAsync(data[i].url); data[i].info = data[i].location + ' • ' + msecs + ' ms'; data[i].msecs = msecs; console.log(data[i].location + ' • ' + msecs + ' ms • ' + data[i].url + '/rpc'); this.availableHosts.push(data[i]); } catch (err) { console.log('Error with RPC: ' + data[i]); } } this.availableHosts.sort((a, b) => a.msecs - b.msecs); this.updateRpc(); }); } } async JSONRPC(method: string, params: Array): Promise { let res = await fetch(this.host, { method: 'POST', mode: 'cors', body: JSON.stringify({ jsonrpc: '2.0', method: method, params: params, id: '1', }), headers: { 'Content-Type': 'application/json' }, }); let resJson = await res.json(); console.log('method', method, resJson); if (resJson.error) { if (resJson.error.message) return { error: resJson.error.message }; return { error: resJson.error }; } return await resJson.result; } setRpcHost(rpcHost: string) { this.host = rpcHost; } setRpcByName(rpcName: string) { this.rpcName = rpcName; if (this.nexus === 'mainnet') this.updateRpc(); } setNexus(nexus: string) { this.nexus = nexus.toLowerCase(); } updateRpc() { if (this.nexus === 'mainnet' && this.availableHosts.length > 0) { console.log('%cUpdate RPC with name ' + this.rpcName, 'font-size: 20px'); if (this.rpcName == 'Auto') { this.host = this.availableHosts[0].url + '/rpc'; } else { const rpc = this.availableHosts.find((h) => h.location == this.rpcName); if (rpc) this.host = rpc.url + '/rpc'; else this.host = this.availableHosts[0].url + '/rpc'; } console.log('%cSet RPC api to ' + this.host, 'font-size: 20px'); } } convertDecimals(amount: number, decimals: number): number { let mult = Math.pow(10, decimals); return amount / mult; } //Returns the account name and balance of given address. async getAccount(account: string, extended: boolean = true): Promise { let params: Array = [account, extended]; return (await this.JSONRPC('getAccount', params)) as Account; } //Returns the accounts name and balance of given addresses. async getAccounts(accounts: string[], extended: boolean = true): Promise { let params: Array = [accounts.join(','), extended]; return (await this.JSONRPC('getAccounts', params)) as Account[]; } //Returns the address that owns a given name. async lookUpName(name: string): Promise { let params: Array = [name]; return (await this.JSONRPC('lookUpName', params)) as string; } //Returns the address that owns a given name. async getAddressesBySymbol(symbol: string, extended: boolean = false): Promise { let params: Array = [symbol, extended]; return (await this.JSONRPC('getAddressesBySymbol', params)) as Account[]; } //Returns the height of a chain. async getBlockHeight(chainInput: string): Promise { let params: Array = [chainInput]; return (await this.JSONRPC('getBlockHeight', params)) as number; } //Returns the number of transactions of given block hash or error if given hash is invalid or is not found. async getBlockTransactionCountByHash(blockHash: string): Promise { let params: Array = [blockHash]; return (await this.JSONRPC('getBlockTransactionCountByHash', params)) as number; } //Returns information about a block by hash. async getBlockByHash(blockHash: string): Promise { let params: Array = [blockHash]; return (await this.JSONRPC('getBlockByHash', params)) as Block; } //Returns a serialized string, containing information about a block by hash. async getRawBlockByHash(blockHash: string): Promise { let params: Array = [blockHash]; return (await this.JSONRPC('getRawBlockByHash', params)) as string; } //Returns information about a block by height and chain. async getBlockByHeight(chainInput: string, height: number): Promise { let params: Array = [chainInput, height]; return (await this.JSONRPC('getBlockByHeight', params)) as Block; } //Returns information about a block by height and chain. async getLatestBlock(chainInput: string): Promise { let params: Array = [chainInput]; return (await this.JSONRPC('getLatestBlock', params)) as Block; } //Returns a serialized string, in hex format, containing information about a block by height and chain. async getRawBlockByHeight(chainInput: string, height: number): Promise { let params: Array = [chainInput, height]; return (await this.JSONRPC('getRawBlockByHeight', params)) as string; } //Returns a serialized string, in hex format, containing information about a block by height and chain. async getRawLatestBlock(chainInput: string): Promise { let params: Array = [chainInput]; return (await this.JSONRPC('getRawLatestBlock', params)) as string; } //Returns the information about a transaction requested by a block hash and transaction index. async getTransactionByBlockHashAndIndex( blockHash: string, index: number ): Promise { let params: Array = [blockHash, index]; return (await this.JSONRPC('getTransactionByBlockHashAndIndex', params)) as TransactionData; } //Returns last X transactions of given address. async getAddressTransactions( account: string, page: number, pageSize: number ): Promise> { let params: Array = [account, page, pageSize]; return (await this.JSONRPC('getAddressTransactions', params)) as Paginated; } //Get number of transactions in a specific address and chain async getAddressTransactionCount(account: string, chainInput: string): Promise { let params: Array = [account, chainInput]; return (await this.JSONRPC('getAddressTransactionCount', params)) as number; } //Allows to broadcast a signed operation on the network, but it's required to build it manually. async sendRawTransaction(txData: string): Promise { let params: Array = [txData]; return (await this.JSONRPC('sendRawTransaction', params)) as string; } //Allows to invoke script based on network state, without state changes. async invokeRawScript(chainInput: string, scriptData: string): Promise