@stacks/network
Advanced tools
Comparing version 4.0.3-beta.0 to 4.1.0
@@ -1,54 +0,2 @@ | ||
import { TransactionVersion, ChainID } from '@stacks/common'; | ||
export declare const HIRO_MAINNET_DEFAULT = "https://stacks-node-api.mainnet.stacks.co"; | ||
export declare const HIRO_TESTNET_DEFAULT = "https://stacks-node-api.testnet.stacks.co"; | ||
export declare const HIRO_MOCKNET_DEFAULT = "http://localhost:3999"; | ||
export interface NetworkConfig { | ||
url: string; | ||
} | ||
export declare const StacksNetworks: readonly ["mainnet", "testnet"]; | ||
export declare type StacksNetworkName = typeof StacksNetworks[number]; | ||
export declare class StacksNetwork { | ||
version: TransactionVersion; | ||
chainId: ChainID; | ||
bnsLookupUrl: string; | ||
broadcastEndpoint: string; | ||
transferFeeEstimateEndpoint: string; | ||
transactionFeeEstimateEndpoint: string; | ||
accountEndpoint: string; | ||
contractAbiEndpoint: string; | ||
readOnlyFunctionCallEndpoint: string; | ||
readonly coreApiUrl: string; | ||
constructor(networkConfig: NetworkConfig); | ||
static fromName: (networkName: StacksNetworkName) => StacksNetwork; | ||
static fromNameOrNetwork: (network: StacksNetworkName | StacksNetwork) => StacksNetwork; | ||
isMainnet: () => boolean; | ||
getBroadcastApiUrl: () => string; | ||
getTransferFeeEstimateApiUrl: () => string; | ||
getTransactionFeeEstimateApiUrl: () => string; | ||
getAccountApiUrl: (address: string) => string; | ||
getAbiApiUrl: (address: string, contract: string) => string; | ||
getReadOnlyFunctionCallApiUrl: (contractAddress: string, contractName: string, functionName: string) => string; | ||
getInfoUrl: () => string; | ||
getBlockTimeInfoUrl: () => string; | ||
getPoxInfoUrl: () => string; | ||
getRewardsUrl: (address: string, options?: any) => string; | ||
getRewardsTotalUrl: (address: string) => string; | ||
getRewardHoldersUrl: (address: string, options?: any) => string; | ||
getStackerInfoUrl: (contractAddress: string, contractName: string) => string; | ||
getNameInfo(fullyQualifiedName: string): Promise<any>; | ||
} | ||
export declare class StacksMainnet extends StacksNetwork { | ||
version: TransactionVersion; | ||
chainId: ChainID; | ||
constructor(networkUrl?: NetworkConfig); | ||
} | ||
export declare class StacksTestnet extends StacksNetwork { | ||
version: TransactionVersion; | ||
chainId: ChainID; | ||
constructor(networkUrl?: NetworkConfig); | ||
} | ||
export declare class StacksMocknet extends StacksNetwork { | ||
version: TransactionVersion; | ||
chainId: ChainID; | ||
constructor(networkUrl?: NetworkConfig); | ||
} | ||
export * from './fetch'; | ||
export * from './network'; |
@@ -1,107 +0,3 @@ | ||
import { TransactionVersion, ChainID, fetchPrivate } from '@stacks/common'; | ||
export const HIRO_MAINNET_DEFAULT = 'https://stacks-node-api.mainnet.stacks.co'; | ||
export const HIRO_TESTNET_DEFAULT = 'https://stacks-node-api.testnet.stacks.co'; | ||
export const HIRO_MOCKNET_DEFAULT = 'http://localhost:3999'; | ||
export const StacksNetworks = ['mainnet', 'testnet']; | ||
export class StacksNetwork { | ||
constructor(networkConfig) { | ||
this.version = TransactionVersion.Mainnet; | ||
this.chainId = ChainID.Mainnet; | ||
this.bnsLookupUrl = 'https://stacks-node-api.mainnet.stacks.co'; | ||
this.broadcastEndpoint = '/v2/transactions'; | ||
this.transferFeeEstimateEndpoint = '/v2/fees/transfer'; | ||
this.transactionFeeEstimateEndpoint = '/v2/fees/transaction'; | ||
this.accountEndpoint = '/v2/accounts'; | ||
this.contractAbiEndpoint = '/v2/contracts/interface'; | ||
this.readOnlyFunctionCallEndpoint = '/v2/contracts/call-read'; | ||
this.isMainnet = () => this.version === TransactionVersion.Mainnet; | ||
this.getBroadcastApiUrl = () => `${this.coreApiUrl}${this.broadcastEndpoint}`; | ||
this.getTransferFeeEstimateApiUrl = () => `${this.coreApiUrl}${this.transferFeeEstimateEndpoint}`; | ||
this.getTransactionFeeEstimateApiUrl = () => `${this.coreApiUrl}${this.transactionFeeEstimateEndpoint}`; | ||
this.getAccountApiUrl = (address) => `${this.coreApiUrl}${this.accountEndpoint}/${address}?proof=0`; | ||
this.getAbiApiUrl = (address, contract) => `${this.coreApiUrl}${this.contractAbiEndpoint}/${address}/${contract}`; | ||
this.getReadOnlyFunctionCallApiUrl = (contractAddress, contractName, functionName) => `${this.coreApiUrl}${this.readOnlyFunctionCallEndpoint}/${contractAddress}/${contractName}/${encodeURIComponent(functionName)}`; | ||
this.getInfoUrl = () => `${this.coreApiUrl}/v2/info`; | ||
this.getBlockTimeInfoUrl = () => `${this.coreApiUrl}/extended/v1/info/network_block_times`; | ||
this.getPoxInfoUrl = () => `${this.coreApiUrl}/v2/pox`; | ||
this.getRewardsUrl = (address, options) => { | ||
let url = `${this.coreApiUrl}/extended/v1/burnchain/rewards/${address}`; | ||
if (options) { | ||
url = `${url}?limit=${options.limit}&offset=${options.offset}`; | ||
} | ||
return url; | ||
}; | ||
this.getRewardsTotalUrl = (address) => `${this.coreApiUrl}/extended/v1/burnchain/rewards/${address}/total`; | ||
this.getRewardHoldersUrl = (address, options) => { | ||
let url = `${this.coreApiUrl}/extended/v1/burnchain/reward_slot_holders/${address}`; | ||
if (options) { | ||
url = `${url}?limit=${options.limit}&offset=${options.offset}`; | ||
} | ||
return url; | ||
}; | ||
this.getStackerInfoUrl = (contractAddress, contractName) => `${this.coreApiUrl}${this.readOnlyFunctionCallEndpoint} | ||
${contractAddress}/${contractName}/get-stacker-info`; | ||
this.coreApiUrl = networkConfig.url; | ||
} | ||
getNameInfo(fullyQualifiedName) { | ||
const nameLookupURL = `${this.bnsLookupUrl}/v1/names/${fullyQualifiedName}`; | ||
return fetchPrivate(nameLookupURL) | ||
.then(resp => { | ||
if (resp.status === 404) { | ||
throw new Error('Name not found'); | ||
} | ||
else if (resp.status !== 200) { | ||
throw new Error(`Bad response status: ${resp.status}`); | ||
} | ||
else { | ||
return resp.json(); | ||
} | ||
}) | ||
.then(nameInfo => { | ||
if (nameInfo.address) { | ||
return Object.assign({}, nameInfo, { address: nameInfo.address }); | ||
} | ||
else { | ||
return nameInfo; | ||
} | ||
}); | ||
} | ||
} | ||
StacksNetwork.fromName = (networkName) => { | ||
switch (networkName) { | ||
case 'mainnet': | ||
return new StacksMainnet(); | ||
case 'testnet': | ||
return new StacksTestnet(); | ||
default: | ||
throw new Error(`Invalid network name provided. Must be one of the following: ${StacksNetworks.join(', ')}`); | ||
} | ||
}; | ||
StacksNetwork.fromNameOrNetwork = (network) => { | ||
if (typeof network !== 'string' && 'version' in network) { | ||
return network; | ||
} | ||
return StacksNetwork.fromName(network); | ||
}; | ||
export class StacksMainnet extends StacksNetwork { | ||
constructor(networkUrl = { url: HIRO_MAINNET_DEFAULT }) { | ||
super(networkUrl); | ||
this.version = TransactionVersion.Mainnet; | ||
this.chainId = ChainID.Mainnet; | ||
} | ||
} | ||
export class StacksTestnet extends StacksNetwork { | ||
constructor(networkUrl = { url: HIRO_TESTNET_DEFAULT }) { | ||
super(networkUrl); | ||
this.version = TransactionVersion.Testnet; | ||
this.chainId = ChainID.Testnet; | ||
} | ||
} | ||
export class StacksMocknet extends StacksNetwork { | ||
constructor(networkUrl = { url: HIRO_MOCKNET_DEFAULT }) { | ||
super(networkUrl); | ||
this.version = TransactionVersion.Testnet; | ||
this.chainId = ChainID.Testnet; | ||
} | ||
} | ||
export * from './fetch'; | ||
export * from './network'; | ||
//# sourceMappingURL=index.js.map |
@@ -1,54 +0,2 @@ | ||
import { TransactionVersion, ChainID } from '@stacks/common'; | ||
export declare const HIRO_MAINNET_DEFAULT = "https://stacks-node-api.mainnet.stacks.co"; | ||
export declare const HIRO_TESTNET_DEFAULT = "https://stacks-node-api.testnet.stacks.co"; | ||
export declare const HIRO_MOCKNET_DEFAULT = "http://localhost:3999"; | ||
export interface NetworkConfig { | ||
url: string; | ||
} | ||
export declare const StacksNetworks: readonly ["mainnet", "testnet"]; | ||
export declare type StacksNetworkName = typeof StacksNetworks[number]; | ||
export declare class StacksNetwork { | ||
version: TransactionVersion; | ||
chainId: ChainID; | ||
bnsLookupUrl: string; | ||
broadcastEndpoint: string; | ||
transferFeeEstimateEndpoint: string; | ||
transactionFeeEstimateEndpoint: string; | ||
accountEndpoint: string; | ||
contractAbiEndpoint: string; | ||
readOnlyFunctionCallEndpoint: string; | ||
readonly coreApiUrl: string; | ||
constructor(networkConfig: NetworkConfig); | ||
static fromName: (networkName: StacksNetworkName) => StacksNetwork; | ||
static fromNameOrNetwork: (network: StacksNetworkName | StacksNetwork) => StacksNetwork; | ||
isMainnet: () => boolean; | ||
getBroadcastApiUrl: () => string; | ||
getTransferFeeEstimateApiUrl: () => string; | ||
getTransactionFeeEstimateApiUrl: () => string; | ||
getAccountApiUrl: (address: string) => string; | ||
getAbiApiUrl: (address: string, contract: string) => string; | ||
getReadOnlyFunctionCallApiUrl: (contractAddress: string, contractName: string, functionName: string) => string; | ||
getInfoUrl: () => string; | ||
getBlockTimeInfoUrl: () => string; | ||
getPoxInfoUrl: () => string; | ||
getRewardsUrl: (address: string, options?: any) => string; | ||
getRewardsTotalUrl: (address: string) => string; | ||
getRewardHoldersUrl: (address: string, options?: any) => string; | ||
getStackerInfoUrl: (contractAddress: string, contractName: string) => string; | ||
getNameInfo(fullyQualifiedName: string): Promise<any>; | ||
} | ||
export declare class StacksMainnet extends StacksNetwork { | ||
version: TransactionVersion; | ||
chainId: ChainID; | ||
constructor(networkUrl?: NetworkConfig); | ||
} | ||
export declare class StacksTestnet extends StacksNetwork { | ||
version: TransactionVersion; | ||
chainId: ChainID; | ||
constructor(networkUrl?: NetworkConfig); | ||
} | ||
export declare class StacksMocknet extends StacksNetwork { | ||
version: TransactionVersion; | ||
chainId: ChainID; | ||
constructor(networkUrl?: NetworkConfig); | ||
} | ||
export * from './fetch'; | ||
export * from './network'; |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.StacksMocknet = exports.StacksTestnet = exports.StacksMainnet = exports.StacksNetwork = exports.StacksNetworks = exports.HIRO_MOCKNET_DEFAULT = exports.HIRO_TESTNET_DEFAULT = exports.HIRO_MAINNET_DEFAULT = void 0; | ||
const common_1 = require("@stacks/common"); | ||
exports.HIRO_MAINNET_DEFAULT = 'https://stacks-node-api.mainnet.stacks.co'; | ||
exports.HIRO_TESTNET_DEFAULT = 'https://stacks-node-api.testnet.stacks.co'; | ||
exports.HIRO_MOCKNET_DEFAULT = 'http://localhost:3999'; | ||
exports.StacksNetworks = ['mainnet', 'testnet']; | ||
class StacksNetwork { | ||
constructor(networkConfig) { | ||
this.version = common_1.TransactionVersion.Mainnet; | ||
this.chainId = common_1.ChainID.Mainnet; | ||
this.bnsLookupUrl = 'https://stacks-node-api.mainnet.stacks.co'; | ||
this.broadcastEndpoint = '/v2/transactions'; | ||
this.transferFeeEstimateEndpoint = '/v2/fees/transfer'; | ||
this.transactionFeeEstimateEndpoint = '/v2/fees/transaction'; | ||
this.accountEndpoint = '/v2/accounts'; | ||
this.contractAbiEndpoint = '/v2/contracts/interface'; | ||
this.readOnlyFunctionCallEndpoint = '/v2/contracts/call-read'; | ||
this.isMainnet = () => this.version === common_1.TransactionVersion.Mainnet; | ||
this.getBroadcastApiUrl = () => `${this.coreApiUrl}${this.broadcastEndpoint}`; | ||
this.getTransferFeeEstimateApiUrl = () => `${this.coreApiUrl}${this.transferFeeEstimateEndpoint}`; | ||
this.getTransactionFeeEstimateApiUrl = () => `${this.coreApiUrl}${this.transactionFeeEstimateEndpoint}`; | ||
this.getAccountApiUrl = (address) => `${this.coreApiUrl}${this.accountEndpoint}/${address}?proof=0`; | ||
this.getAbiApiUrl = (address, contract) => `${this.coreApiUrl}${this.contractAbiEndpoint}/${address}/${contract}`; | ||
this.getReadOnlyFunctionCallApiUrl = (contractAddress, contractName, functionName) => `${this.coreApiUrl}${this.readOnlyFunctionCallEndpoint}/${contractAddress}/${contractName}/${encodeURIComponent(functionName)}`; | ||
this.getInfoUrl = () => `${this.coreApiUrl}/v2/info`; | ||
this.getBlockTimeInfoUrl = () => `${this.coreApiUrl}/extended/v1/info/network_block_times`; | ||
this.getPoxInfoUrl = () => `${this.coreApiUrl}/v2/pox`; | ||
this.getRewardsUrl = (address, options) => { | ||
let url = `${this.coreApiUrl}/extended/v1/burnchain/rewards/${address}`; | ||
if (options) { | ||
url = `${url}?limit=${options.limit}&offset=${options.offset}`; | ||
} | ||
return url; | ||
}; | ||
this.getRewardsTotalUrl = (address) => `${this.coreApiUrl}/extended/v1/burnchain/rewards/${address}/total`; | ||
this.getRewardHoldersUrl = (address, options) => { | ||
let url = `${this.coreApiUrl}/extended/v1/burnchain/reward_slot_holders/${address}`; | ||
if (options) { | ||
url = `${url}?limit=${options.limit}&offset=${options.offset}`; | ||
} | ||
return url; | ||
}; | ||
this.getStackerInfoUrl = (contractAddress, contractName) => `${this.coreApiUrl}${this.readOnlyFunctionCallEndpoint} | ||
${contractAddress}/${contractName}/get-stacker-info`; | ||
this.coreApiUrl = networkConfig.url; | ||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { | ||
if (k2 === undefined) k2 = k; | ||
var desc = Object.getOwnPropertyDescriptor(m, k); | ||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { | ||
desc = { enumerable: true, get: function() { return m[k]; } }; | ||
} | ||
getNameInfo(fullyQualifiedName) { | ||
const nameLookupURL = `${this.bnsLookupUrl}/v1/names/${fullyQualifiedName}`; | ||
return (0, common_1.fetchPrivate)(nameLookupURL) | ||
.then(resp => { | ||
if (resp.status === 404) { | ||
throw new Error('Name not found'); | ||
} | ||
else if (resp.status !== 200) { | ||
throw new Error(`Bad response status: ${resp.status}`); | ||
} | ||
else { | ||
return resp.json(); | ||
} | ||
}) | ||
.then(nameInfo => { | ||
if (nameInfo.address) { | ||
return Object.assign({}, nameInfo, { address: nameInfo.address }); | ||
} | ||
else { | ||
return nameInfo; | ||
} | ||
}); | ||
} | ||
} | ||
exports.StacksNetwork = StacksNetwork; | ||
StacksNetwork.fromName = (networkName) => { | ||
switch (networkName) { | ||
case 'mainnet': | ||
return new StacksMainnet(); | ||
case 'testnet': | ||
return new StacksTestnet(); | ||
default: | ||
throw new Error(`Invalid network name provided. Must be one of the following: ${exports.StacksNetworks.join(', ')}`); | ||
} | ||
Object.defineProperty(o, k2, desc); | ||
}) : (function(o, m, k, k2) { | ||
if (k2 === undefined) k2 = k; | ||
o[k2] = m[k]; | ||
})); | ||
var __exportStar = (this && this.__exportStar) || function(m, exports) { | ||
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); | ||
}; | ||
StacksNetwork.fromNameOrNetwork = (network) => { | ||
if (typeof network !== 'string' && 'version' in network) { | ||
return network; | ||
} | ||
return StacksNetwork.fromName(network); | ||
}; | ||
class StacksMainnet extends StacksNetwork { | ||
constructor(networkUrl = { url: exports.HIRO_MAINNET_DEFAULT }) { | ||
super(networkUrl); | ||
this.version = common_1.TransactionVersion.Mainnet; | ||
this.chainId = common_1.ChainID.Mainnet; | ||
} | ||
} | ||
exports.StacksMainnet = StacksMainnet; | ||
class StacksTestnet extends StacksNetwork { | ||
constructor(networkUrl = { url: exports.HIRO_TESTNET_DEFAULT }) { | ||
super(networkUrl); | ||
this.version = common_1.TransactionVersion.Testnet; | ||
this.chainId = common_1.ChainID.Testnet; | ||
} | ||
} | ||
exports.StacksTestnet = StacksTestnet; | ||
class StacksMocknet extends StacksNetwork { | ||
constructor(networkUrl = { url: exports.HIRO_MOCKNET_DEFAULT }) { | ||
super(networkUrl); | ||
this.version = common_1.TransactionVersion.Testnet; | ||
this.chainId = common_1.ChainID.Testnet; | ||
} | ||
} | ||
exports.StacksMocknet = StacksMocknet; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
__exportStar(require("./fetch"), exports); | ||
__exportStar(require("./network"), exports); | ||
//# sourceMappingURL=index.js.map |
@@ -1,1 +0,1 @@ | ||
window.global=window;import{TransactionVersion as t,ChainID as s,fetchPrivate as e}from"@stacks/common/dist/polyfill";const n="https://stacks-node-api.mainnet.stacks.co",i="https://stacks-node-api.testnet.stacks.co",r="http://localhost:3999",o=["mainnet","testnet"];class a{constructor(e){this.version=t.Mainnet,this.chainId=s.Mainnet,this.bnsLookupUrl="https://stacks-node-api.mainnet.stacks.co",this.broadcastEndpoint="/v2/transactions",this.transferFeeEstimateEndpoint="/v2/fees/transfer",this.transactionFeeEstimateEndpoint="/v2/fees/transaction",this.accountEndpoint="/v2/accounts",this.contractAbiEndpoint="/v2/contracts/interface",this.readOnlyFunctionCallEndpoint="/v2/contracts/call-read",this.isMainnet=()=>this.version===t.Mainnet,this.getBroadcastApiUrl=()=>`${this.coreApiUrl}${this.broadcastEndpoint}`,this.getTransferFeeEstimateApiUrl=()=>`${this.coreApiUrl}${this.transferFeeEstimateEndpoint}`,this.getTransactionFeeEstimateApiUrl=()=>`${this.coreApiUrl}${this.transactionFeeEstimateEndpoint}`,this.getAccountApiUrl=t=>`${this.coreApiUrl}${this.accountEndpoint}/${t}?proof=0`,this.getAbiApiUrl=(t,s)=>`${this.coreApiUrl}${this.contractAbiEndpoint}/${t}/${s}`,this.getReadOnlyFunctionCallApiUrl=(t,s,e)=>`${this.coreApiUrl}${this.readOnlyFunctionCallEndpoint}/${t}/${s}/${encodeURIComponent(e)}`,this.getInfoUrl=()=>`${this.coreApiUrl}/v2/info`,this.getBlockTimeInfoUrl=()=>`${this.coreApiUrl}/extended/v1/info/network_block_times`,this.getPoxInfoUrl=()=>`${this.coreApiUrl}/v2/pox`,this.getRewardsUrl=(t,s)=>{let e=`${this.coreApiUrl}/extended/v1/burnchain/rewards/${t}`;return s&&(e=`${e}?limit=${s.limit}&offset=${s.offset}`),e},this.getRewardsTotalUrl=t=>`${this.coreApiUrl}/extended/v1/burnchain/rewards/${t}/total`,this.getRewardHoldersUrl=(t,s)=>{let e=`${this.coreApiUrl}/extended/v1/burnchain/reward_slot_holders/${t}`;return s&&(e=`${e}?limit=${s.limit}&offset=${s.offset}`),e},this.getStackerInfoUrl=(t,s)=>`${this.coreApiUrl}${this.readOnlyFunctionCallEndpoint}\n ${t}/${s}/get-stacker-info`,this.coreApiUrl=e.url}getNameInfo(t){const s=`${this.bnsLookupUrl}/v1/names/${t}`;return e(s).then((t=>{if(404===t.status)throw new Error("Name not found");if(200!==t.status)throw new Error(`Bad response status: ${t.status}`);return t.json()})).then((t=>t.address?Object.assign({},t,{address:t.address}):t))}}a.fromName=t=>{switch(t){case"mainnet":return new c;case"testnet":return new l;default:throw new Error(`Invalid network name provided. Must be one of the following: ${o.join(", ")}`)}},a.fromNameOrNetwork=t=>"string"!=typeof t&&"version"in t?t:a.fromName(t);class c extends a{constructor(e={url:"https://stacks-node-api.mainnet.stacks.co"}){super(e),this.version=t.Mainnet,this.chainId=s.Mainnet}}class l extends a{constructor(e={url:"https://stacks-node-api.testnet.stacks.co"}){super(e),this.version=t.Testnet,this.chainId=s.Testnet}}class h extends a{constructor(e={url:"http://localhost:3999"}){super(e),this.version=t.Testnet,this.chainId=s.Testnet}}export{n as HIRO_MAINNET_DEFAULT,r as HIRO_MOCKNET_DEFAULT,i as HIRO_TESTNET_DEFAULT,c as StacksMainnet,h as StacksMocknet,a as StacksNetwork,o as StacksNetworks,l as StacksTestnet}; | ||
window.global=window;import{TransactionVersion as t,ChainID as e}from"@stacks/common/dist/polyfill";var r="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};!function(t){!function(e){var r="URLSearchParams"in t,n="Symbol"in t&&"iterator"in Symbol,o="FileReader"in t&&"Blob"in t&&function(){try{return new Blob,!0}catch(t){return!1}}(),i="FormData"in t,s="ArrayBuffer"in t;if(s)var a=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],h=ArrayBuffer.isView||function(t){return t&&a.indexOf(Object.prototype.toString.call(t))>-1};function c(t){if("string"!=typeof t&&(t=String(t)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(t))throw new TypeError("Invalid character in header field name");return t.toLowerCase()}function l(t){return"string"!=typeof t&&(t=String(t)),t}function d(t){var e={next:function(){var e=t.shift();return{done:void 0===e,value:e}}};return n&&(e[Symbol.iterator]=function(){return e}),e}function u(t){this.map={},t instanceof u?t.forEach((function(t,e){this.append(e,t)}),this):Array.isArray(t)?t.forEach((function(t){this.append(t[0],t[1])}),this):t&&Object.getOwnPropertyNames(t).forEach((function(e){this.append(e,t[e])}),this)}function f(t){if(t.bodyUsed)return Promise.reject(new TypeError("Already read"));t.bodyUsed=!0}function p(t){return new Promise((function(e,r){t.onload=function(){e(t.result)},t.onerror=function(){r(t.error)}}))}function y(t){var e=new FileReader,r=p(e);return e.readAsArrayBuffer(t),r}function b(t){if(t.slice)return t.slice(0);var e=new Uint8Array(t.byteLength);return e.set(new Uint8Array(t)),e.buffer}function m(){return this.bodyUsed=!1,this._initBody=function(t){var e;this._bodyInit=t,t?"string"==typeof t?this._bodyText=t:o&&Blob.prototype.isPrototypeOf(t)?this._bodyBlob=t:i&&FormData.prototype.isPrototypeOf(t)?this._bodyFormData=t:r&&URLSearchParams.prototype.isPrototypeOf(t)?this._bodyText=t.toString():s&&o&&(e=t)&&DataView.prototype.isPrototypeOf(e)?(this._bodyArrayBuffer=b(t.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):s&&(ArrayBuffer.prototype.isPrototypeOf(t)||h(t))?this._bodyArrayBuffer=b(t):this._bodyText=t=Object.prototype.toString.call(t):this._bodyText="",this.headers.get("content-type")||("string"==typeof t?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):r&&URLSearchParams.prototype.isPrototypeOf(t)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},o&&(this.blob=function(){var t=f(this);if(t)return t;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?f(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(y)}),this.text=function(){var t,e,r,n=f(this);if(n)return n;if(this._bodyBlob)return t=this._bodyBlob,e=new FileReader,r=p(e),e.readAsText(t),r;if(this._bodyArrayBuffer)return Promise.resolve(function(t){for(var e=new Uint8Array(t),r=new Array(e.length),n=0;n<e.length;n++)r[n]=String.fromCharCode(e[n]);return r.join("")}(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},i&&(this.formData=function(){return this.text().then(g)}),this.json=function(){return this.text().then(JSON.parse)},this}u.prototype.append=function(t,e){t=c(t),e=l(e);var r=this.map[t];this.map[t]=r?r+", "+e:e},u.prototype.delete=function(t){delete this.map[c(t)]},u.prototype.get=function(t){return t=c(t),this.has(t)?this.map[t]:null},u.prototype.has=function(t){return this.map.hasOwnProperty(c(t))},u.prototype.set=function(t,e){this.map[c(t)]=l(e)},u.prototype.forEach=function(t,e){for(var r in this.map)this.map.hasOwnProperty(r)&&t.call(e,this.map[r],r,this)},u.prototype.keys=function(){var t=[];return this.forEach((function(e,r){t.push(r)})),d(t)},u.prototype.values=function(){var t=[];return this.forEach((function(e){t.push(e)})),d(t)},u.prototype.entries=function(){var t=[];return this.forEach((function(e,r){t.push([r,e])})),d(t)},n&&(u.prototype[Symbol.iterator]=u.prototype.entries);var w=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function v(t,e){var r,n,o=(e=e||{}).body;if(t instanceof v){if(t.bodyUsed)throw new TypeError("Already read");this.url=t.url,this.credentials=t.credentials,e.headers||(this.headers=new u(t.headers)),this.method=t.method,this.mode=t.mode,this.signal=t.signal,o||null==t._bodyInit||(o=t._bodyInit,t.bodyUsed=!0)}else this.url=String(t);if(this.credentials=e.credentials||this.credentials||"same-origin",!e.headers&&this.headers||(this.headers=new u(e.headers)),this.method=(r=e.method||this.method||"GET",n=r.toUpperCase(),w.indexOf(n)>-1?n:r),this.mode=e.mode||this.mode||null,this.signal=e.signal||this.signal,this.referrer=null,("GET"===this.method||"HEAD"===this.method)&&o)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(o)}function g(t){var e=new FormData;return t.trim().split("&").forEach((function(t){if(t){var r=t.split("="),n=r.shift().replace(/\+/g," "),o=r.join("=").replace(/\+/g," ");e.append(decodeURIComponent(n),decodeURIComponent(o))}})),e}function E(t,e){e||(e={}),this.type="default",this.status=void 0===e.status?200:e.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in e?e.statusText:"OK",this.headers=new u(e.headers),this.url=e.url||"",this._initBody(t)}v.prototype.clone=function(){return new v(this,{body:this._bodyInit})},m.call(v.prototype),m.call(E.prototype),E.prototype.clone=function(){return new E(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new u(this.headers),url:this.url})},E.error=function(){var t=new E(null,{status:0,statusText:""});return t.type="error",t};var A=[301,302,303,307,308];E.redirect=function(t,e){if(-1===A.indexOf(e))throw new RangeError("Invalid status code");return new E(null,{status:e,headers:{location:t}})},e.DOMException=t.DOMException;try{new e.DOMException}catch(t){e.DOMException=function(t,e){this.message=t,this.name=e;var r=Error(t);this.stack=r.stack},e.DOMException.prototype=Object.create(Error.prototype),e.DOMException.prototype.constructor=e.DOMException}function U(t,r){return new Promise((function(n,i){var s=new v(t,r);if(s.signal&&s.signal.aborted)return i(new e.DOMException("Aborted","AbortError"));var a=new XMLHttpRequest;function h(){a.abort()}a.onload=function(){var t,e,r={status:a.status,statusText:a.statusText,headers:(t=a.getAllResponseHeaders()||"",e=new u,t.replace(/\r?\n[\t ]+/g," ").split(/\r?\n/).forEach((function(t){var r=t.split(":"),n=r.shift().trim();if(n){var o=r.join(":").trim();e.append(n,o)}})),e)};r.url="responseURL"in a?a.responseURL:r.headers.get("X-Request-URL");var o="response"in a?a.response:a.responseText;n(new E(o,r))},a.onerror=function(){i(new TypeError("Network request failed"))},a.ontimeout=function(){i(new TypeError("Network request failed"))},a.onabort=function(){i(new e.DOMException("Aborted","AbortError"))},a.open(s.method,s.url,!0),"include"===s.credentials?a.withCredentials=!0:"omit"===s.credentials&&(a.withCredentials=!1),"responseType"in a&&o&&(a.responseType="blob"),s.headers.forEach((function(t,e){a.setRequestHeader(e,t)})),s.signal&&(s.signal.addEventListener("abort",h),a.onreadystatechange=function(){4===a.readyState&&s.signal.removeEventListener("abort",h)}),a.send(void 0===s._bodyInit?null:s._bodyInit)}))}U.polyfill=!0,t.fetch||(t.fetch=U,t.Headers=u,t.Request=v,t.Response=E),e.Headers=u,e.Request=v,e.Response=E,e.fetch=U,Object.defineProperty(e,"__esModule",{value:!0})}({})}("undefined"!=typeof self?self:r);const n={referrerPolicy:"origin"},o=()=>n,i=t=>Object.assign(n,t);async function s(t,e){const r={};Object.assign(r,e,n);return await fetch(t,r)}function a(t,e){return"string"==typeof e?e===t:e.exec(t)}function h({apiKey:t,host:e=/(.*)api(.*)\.stacks\.co$/i,httpHeader:r="x-api-key"}){return{pre:n=>{if(!a(new URL(n.url).host,e))return;const o=new Headers(n.init.headers);o.set(r,t),n.init.headers=o}}}function c(...t){const{fetchLib:e,middlewares:r}=function(t){let e=s,r=[];return t.length>0&&"function"==typeof t[0]&&(e=t.shift()),t.length>0&&(r=t),{fetchLib:e,middlewares:r}}(t);return async(t,n)=>{var o;let i={url:t,init:null!=n?n:{}};for(const t of r)if("function"==typeof t.pre){const r=await Promise.resolve(t.pre(Object.assign({fetch:e},i)));i=null!=r?r:i}let s=await e(i.url,i.init);for(const t of r)if("function"==typeof t.post){const r=await Promise.resolve(t.post({fetch:e,url:i.url,init:i.init,response:null!==(o=null==s?void 0:s.clone())&&void 0!==o?o:s}));s=null!=r?r:s}return s}}const l="https://stacks-node-api.mainnet.stacks.co",d="https://stacks-node-api.testnet.stacks.co",u="http://localhost:3999",f=["mainnet","testnet"];class p{constructor(r){var n;this.version=t.Mainnet,this.chainId=e.Mainnet,this.bnsLookupUrl="https://stacks-node-api.mainnet.stacks.co",this.broadcastEndpoint="/v2/transactions",this.transferFeeEstimateEndpoint="/v2/fees/transfer",this.transactionFeeEstimateEndpoint="/v2/fees/transaction",this.accountEndpoint="/v2/accounts",this.contractAbiEndpoint="/v2/contracts/interface",this.readOnlyFunctionCallEndpoint="/v2/contracts/call-read",this.isMainnet=()=>this.version===t.Mainnet,this.getBroadcastApiUrl=()=>`${this.coreApiUrl}${this.broadcastEndpoint}`,this.getTransferFeeEstimateApiUrl=()=>`${this.coreApiUrl}${this.transferFeeEstimateEndpoint}`,this.getTransactionFeeEstimateApiUrl=()=>`${this.coreApiUrl}${this.transactionFeeEstimateEndpoint}`,this.getAccountApiUrl=t=>`${this.coreApiUrl}${this.accountEndpoint}/${t}?proof=0`,this.getAbiApiUrl=(t,e)=>`${this.coreApiUrl}${this.contractAbiEndpoint}/${t}/${e}`,this.getReadOnlyFunctionCallApiUrl=(t,e,r)=>`${this.coreApiUrl}${this.readOnlyFunctionCallEndpoint}/${t}/${e}/${encodeURIComponent(r)}`,this.getInfoUrl=()=>`${this.coreApiUrl}/v2/info`,this.getBlockTimeInfoUrl=()=>`${this.coreApiUrl}/extended/v1/info/network_block_times`,this.getPoxInfoUrl=()=>`${this.coreApiUrl}/v2/pox`,this.getRewardsUrl=(t,e)=>{let r=`${this.coreApiUrl}/extended/v1/burnchain/rewards/${t}`;return e&&(r=`${r}?limit=${e.limit}&offset=${e.offset}`),r},this.getRewardsTotalUrl=t=>`${this.coreApiUrl}/extended/v1/burnchain/rewards/${t}/total`,this.getRewardHoldersUrl=(t,e)=>{let r=`${this.coreApiUrl}/extended/v1/burnchain/reward_slot_holders/${t}`;return e&&(r=`${r}?limit=${e.limit}&offset=${e.offset}`),r},this.getStackerInfoUrl=(t,e)=>`${this.coreApiUrl}${this.readOnlyFunctionCallEndpoint}\n ${t}/${e}/get-stacker-info`,this.coreApiUrl=r.url,this.fetchFn=null!==(n=r.fetchFn)&&void 0!==n?n:c()}getNameInfo(t){const e=`${this.bnsLookupUrl}/v1/names/${t}`;return this.fetchFn(e).then((t=>{if(404===t.status)throw new Error("Name not found");if(200!==t.status)throw new Error(`Bad response status: ${t.status}`);return t.json()})).then((t=>t.address?Object.assign({},t,{address:t.address}):t))}}p.fromName=t=>{switch(t){case"mainnet":return new y;case"testnet":return new b;default:throw new Error(`Invalid network name provided. Must be one of the following: ${f.join(", ")}`)}},p.fromNameOrNetwork=t=>"string"!=typeof t&&"version"in t?t:p.fromName(t);class y extends p{constructor(r){var n;super({url:null!==(n=null==r?void 0:r.url)&&void 0!==n?n:"https://stacks-node-api.mainnet.stacks.co",fetchFn:null==r?void 0:r.fetchFn}),this.version=t.Mainnet,this.chainId=e.Mainnet}}class b extends p{constructor(r){var n;super({url:null!==(n=null==r?void 0:r.url)&&void 0!==n?n:"https://stacks-node-api.testnet.stacks.co",fetchFn:null==r?void 0:r.fetchFn}),this.version=t.Testnet,this.chainId=e.Testnet}}class m extends p{constructor(r){var n;super({url:null!==(n=null==r?void 0:r.url)&&void 0!==n?n:"http://localhost:3999",fetchFn:null==r?void 0:r.fetchFn}),this.version=t.Testnet,this.chainId=e.Testnet}}export{l as HIRO_MAINNET_DEFAULT,u as HIRO_MOCKNET_DEFAULT,d as HIRO_TESTNET_DEFAULT,y as StacksMainnet,m as StacksMocknet,p as StacksNetwork,f as StacksNetworks,b as StacksTestnet,h as createApiKeyMiddleware,c as createFetchFn,s as fetchWrapper,o as getFetchOptions,a as hostMatches,i as setFetchOptions}; |
@@ -1,2 +0,2 @@ | ||
!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.StacksNetwork=e():t.StacksNetwork=e()}(this,(()=>(()=>{var t={616:function(){!function(t){!function(e){var r="URLSearchParams"in t,n="Symbol"in t&&"iterator"in Symbol,o="FileReader"in t&&"Blob"in t&&function(){try{return new Blob,!0}catch(t){return!1}}(),i="FormData"in t,s="ArrayBuffer"in t;if(s)var a=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],c=ArrayBuffer.isView||function(t){return t&&a.indexOf(Object.prototype.toString.call(t))>-1};function h(t){if("string"!=typeof t&&(t=String(t)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(t))throw new TypeError("Invalid character in header field name");return t.toLowerCase()}function d(t){return"string"!=typeof t&&(t=String(t)),t}function u(t){var e={next:function(){var e=t.shift();return{done:void 0===e,value:e}}};return n&&(e[Symbol.iterator]=function(){return e}),e}function l(t){this.map={},t instanceof l?t.forEach((function(t,e){this.append(e,t)}),this):Array.isArray(t)?t.forEach((function(t){this.append(t[0],t[1])}),this):t&&Object.getOwnPropertyNames(t).forEach((function(e){this.append(e,t[e])}),this)}function p(t){if(t.bodyUsed)return Promise.reject(new TypeError("Already read"));t.bodyUsed=!0}function f(t){return new Promise((function(e,r){t.onload=function(){e(t.result)},t.onerror=function(){r(t.error)}}))}function y(t){var e=new FileReader,r=f(e);return e.readAsArrayBuffer(t),r}function b(t){if(t.slice)return t.slice(0);var e=new Uint8Array(t.byteLength);return e.set(new Uint8Array(t)),e.buffer}function m(){return this.bodyUsed=!1,this._initBody=function(t){var e;this._bodyInit=t,t?"string"==typeof t?this._bodyText=t:o&&Blob.prototype.isPrototypeOf(t)?this._bodyBlob=t:i&&FormData.prototype.isPrototypeOf(t)?this._bodyFormData=t:r&&URLSearchParams.prototype.isPrototypeOf(t)?this._bodyText=t.toString():s&&o&&(e=t)&&DataView.prototype.isPrototypeOf(e)?(this._bodyArrayBuffer=b(t.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):s&&(ArrayBuffer.prototype.isPrototypeOf(t)||c(t))?this._bodyArrayBuffer=b(t):this._bodyText=t=Object.prototype.toString.call(t):this._bodyText="",this.headers.get("content-type")||("string"==typeof t?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):r&&URLSearchParams.prototype.isPrototypeOf(t)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},o&&(this.blob=function(){var t=p(this);if(t)return t;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?p(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(y)}),this.text=function(){var t,e,r,n=p(this);if(n)return n;if(this._bodyBlob)return t=this._bodyBlob,r=f(e=new FileReader),e.readAsText(t),r;if(this._bodyArrayBuffer)return Promise.resolve(function(t){for(var e=new Uint8Array(t),r=new Array(e.length),n=0;n<e.length;n++)r[n]=String.fromCharCode(e[n]);return r.join("")}(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},i&&(this.formData=function(){return this.text().then(E)}),this.json=function(){return this.text().then(JSON.parse)},this}l.prototype.append=function(t,e){t=h(t),e=d(e);var r=this.map[t];this.map[t]=r?r+", "+e:e},l.prototype.delete=function(t){delete this.map[h(t)]},l.prototype.get=function(t){return t=h(t),this.has(t)?this.map[t]:null},l.prototype.has=function(t){return this.map.hasOwnProperty(h(t))},l.prototype.set=function(t,e){this.map[h(t)]=d(e)},l.prototype.forEach=function(t,e){for(var r in this.map)this.map.hasOwnProperty(r)&&t.call(e,this.map[r],r,this)},l.prototype.keys=function(){var t=[];return this.forEach((function(e,r){t.push(r)})),u(t)},l.prototype.values=function(){var t=[];return this.forEach((function(e){t.push(e)})),u(t)},l.prototype.entries=function(){var t=[];return this.forEach((function(e,r){t.push([r,e])})),u(t)},n&&(l.prototype[Symbol.iterator]=l.prototype.entries);var w=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function v(t,e){var r,n,o=(e=e||{}).body;if(t instanceof v){if(t.bodyUsed)throw new TypeError("Already read");this.url=t.url,this.credentials=t.credentials,e.headers||(this.headers=new l(t.headers)),this.method=t.method,this.mode=t.mode,this.signal=t.signal,o||null==t._bodyInit||(o=t._bodyInit,t.bodyUsed=!0)}else this.url=String(t);if(this.credentials=e.credentials||this.credentials||"same-origin",!e.headers&&this.headers||(this.headers=new l(e.headers)),this.method=(n=(r=e.method||this.method||"GET").toUpperCase(),w.indexOf(n)>-1?n:r),this.mode=e.mode||this.mode||null,this.signal=e.signal||this.signal,this.referrer=null,("GET"===this.method||"HEAD"===this.method)&&o)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(o)}function E(t){var e=new FormData;return t.trim().split("&").forEach((function(t){if(t){var r=t.split("="),n=r.shift().replace(/\+/g," "),o=r.join("=").replace(/\+/g," ");e.append(decodeURIComponent(n),decodeURIComponent(o))}})),e}function A(t,e){e||(e={}),this.type="default",this.status=void 0===e.status?200:e.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in e?e.statusText:"OK",this.headers=new l(e.headers),this.url=e.url||"",this._initBody(t)}v.prototype.clone=function(){return new v(this,{body:this._bodyInit})},m.call(v.prototype),m.call(A.prototype),A.prototype.clone=function(){return new A(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new l(this.headers),url:this.url})},A.error=function(){var t=new A(null,{status:0,statusText:""});return t.type="error",t};var g=[301,302,303,307,308];A.redirect=function(t,e){if(-1===g.indexOf(e))throw new RangeError("Invalid status code");return new A(null,{status:e,headers:{location:t}})},e.DOMException=t.DOMException;try{new e.DOMException}catch(t){e.DOMException=function(t,e){this.message=t,this.name=e;var r=Error(t);this.stack=r.stack},e.DOMException.prototype=Object.create(Error.prototype),e.DOMException.prototype.constructor=e.DOMException}function T(t,r){return new Promise((function(n,i){var s=new v(t,r);if(s.signal&&s.signal.aborted)return i(new e.DOMException("Aborted","AbortError"));var a=new XMLHttpRequest;function c(){a.abort()}a.onload=function(){var t,e,r={status:a.status,statusText:a.statusText,headers:(t=a.getAllResponseHeaders()||"",e=new l,t.replace(/\r?\n[\t ]+/g," ").split(/\r?\n/).forEach((function(t){var r=t.split(":"),n=r.shift().trim();if(n){var o=r.join(":").trim();e.append(n,o)}})),e)};r.url="responseURL"in a?a.responseURL:r.headers.get("X-Request-URL");var o="response"in a?a.response:a.responseText;n(new A(o,r))},a.onerror=function(){i(new TypeError("Network request failed"))},a.ontimeout=function(){i(new TypeError("Network request failed"))},a.onabort=function(){i(new e.DOMException("Aborted","AbortError"))},a.open(s.method,s.url,!0),"include"===s.credentials?a.withCredentials=!0:"omit"===s.credentials&&(a.withCredentials=!1),"responseType"in a&&o&&(a.responseType="blob"),s.headers.forEach((function(t,e){a.setRequestHeader(e,t)})),s.signal&&(s.signal.addEventListener("abort",c),a.onreadystatechange=function(){4===a.readyState&&s.signal.removeEventListener("abort",c)}),a.send(void 0===s._bodyInit?null:s._bodyInit)}))}T.polyfill=!0,t.fetch||(t.fetch=T,t.Headers=l,t.Request=v,t.Response=A),e.Headers=l,e.Request=v,e.Response=A,e.fetch=T,Object.defineProperty(e,"__esModule",{value:!0})}({})}("undefined"!=typeof self?self:this)}},e={};function r(n){var o=e[n];if(void 0!==o)return o.exports;var i=e[n]={exports:{}};return t[n].call(i.exports,i,i.exports,r),i.exports}r.d=(t,e)=>{for(var n in e)r.o(e,n)&&!r.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:e[n]})},r.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})};var n={};return(()=>{"use strict";var t,e;r.r(n),r.d(n,{HIRO_MAINNET_DEFAULT:()=>i,HIRO_MOCKNET_DEFAULT:()=>a,HIRO_TESTNET_DEFAULT:()=>s,StacksMainnet:()=>u,StacksMocknet:()=>p,StacksNetwork:()=>d,StacksNetworks:()=>c,StacksTestnet:()=>l}),function(t){t[t.Testnet=2147483648]="Testnet",t[t.Mainnet=1]="Mainnet"}(t||(t={})),function(t){t[t.Mainnet=0]="Mainnet",t[t.Testnet=128]="Testnet"}(e||(e={})),r(616);const o={referrerPolicy:"origin"},i="https://stacks-node-api.mainnet.stacks.co",s="https://stacks-node-api.testnet.stacks.co",a="http://localhost:3999",c=["mainnet","testnet"],h=class{constructor(r){this.version=e.Mainnet,this.chainId=t.Mainnet,this.bnsLookupUrl="https://stacks-node-api.mainnet.stacks.co",this.broadcastEndpoint="/v2/transactions",this.transferFeeEstimateEndpoint="/v2/fees/transfer",this.transactionFeeEstimateEndpoint="/v2/fees/transaction",this.accountEndpoint="/v2/accounts",this.contractAbiEndpoint="/v2/contracts/interface",this.readOnlyFunctionCallEndpoint="/v2/contracts/call-read",this.isMainnet=()=>this.version===e.Mainnet,this.getBroadcastApiUrl=()=>`${this.coreApiUrl}${this.broadcastEndpoint}`,this.getTransferFeeEstimateApiUrl=()=>`${this.coreApiUrl}${this.transferFeeEstimateEndpoint}`,this.getTransactionFeeEstimateApiUrl=()=>`${this.coreApiUrl}${this.transactionFeeEstimateEndpoint}`,this.getAccountApiUrl=t=>`${this.coreApiUrl}${this.accountEndpoint}/${t}?proof=0`,this.getAbiApiUrl=(t,e)=>`${this.coreApiUrl}${this.contractAbiEndpoint}/${t}/${e}`,this.getReadOnlyFunctionCallApiUrl=(t,e,r)=>`${this.coreApiUrl}${this.readOnlyFunctionCallEndpoint}/${t}/${e}/${encodeURIComponent(r)}`,this.getInfoUrl=()=>`${this.coreApiUrl}/v2/info`,this.getBlockTimeInfoUrl=()=>`${this.coreApiUrl}/extended/v1/info/network_block_times`,this.getPoxInfoUrl=()=>`${this.coreApiUrl}/v2/pox`,this.getRewardsUrl=(t,e)=>{let r=`${this.coreApiUrl}/extended/v1/burnchain/rewards/${t}`;return e&&(r=`${r}?limit=${e.limit}&offset=${e.offset}`),r},this.getRewardsTotalUrl=t=>`${this.coreApiUrl}/extended/v1/burnchain/rewards/${t}/total`,this.getRewardHoldersUrl=(t,e)=>{let r=`${this.coreApiUrl}/extended/v1/burnchain/reward_slot_holders/${t}`;return e&&(r=`${r}?limit=${e.limit}&offset=${e.offset}`),r},this.getStackerInfoUrl=(t,e)=>`${this.coreApiUrl}${this.readOnlyFunctionCallEndpoint}\n ${t}/${e}/get-stacker-info`,this.coreApiUrl=r.url}getNameInfo(t){return async function(t,e){const r={};return Object.assign(r,void 0,o),await fetch(t,r)}(`${this.bnsLookupUrl}/v1/names/${t}`).then((t=>{if(404===t.status)throw new Error("Name not found");if(200!==t.status)throw new Error(`Bad response status: ${t.status}`);return t.json()})).then((t=>t.address?Object.assign({},t,{address:t.address}):t))}};let d=h;d.fromName=t=>{switch(t){case"mainnet":return new u;case"testnet":return new l;default:throw new Error(`Invalid network name provided. Must be one of the following: ${c.join(", ")}`)}},d.fromNameOrNetwork=t=>"string"!=typeof t&&"version"in t?t:h.fromName(t);class u extends d{constructor(r={url:i}){super(r),this.version=e.Mainnet,this.chainId=t.Mainnet}}class l extends d{constructor(r={url:s}){super(r),this.version=e.Testnet,this.chainId=t.Testnet}}class p extends d{constructor(r={url:a}){super(r),this.version=e.Testnet,this.chainId=t.Testnet}}})(),n})())); | ||
!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.StacksNetwork=e():t.StacksNetwork=e()}(this,(()=>(()=>{var t={616:function(){!function(t){!function(e){var r="URLSearchParams"in t,n="Symbol"in t&&"iterator"in Symbol,o="FileReader"in t&&"Blob"in t&&function(){try{return new Blob,!0}catch(t){return!1}}(),i="FormData"in t,s="ArrayBuffer"in t;if(s)var a=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],c=ArrayBuffer.isView||function(t){return t&&a.indexOf(Object.prototype.toString.call(t))>-1};function h(t){if("string"!=typeof t&&(t=String(t)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(t))throw new TypeError("Invalid character in header field name");return t.toLowerCase()}function l(t){return"string"!=typeof t&&(t=String(t)),t}function u(t){var e={next:function(){var e=t.shift();return{done:void 0===e,value:e}}};return n&&(e[Symbol.iterator]=function(){return e}),e}function f(t){this.map={},t instanceof f?t.forEach((function(t,e){this.append(e,t)}),this):Array.isArray(t)?t.forEach((function(t){this.append(t[0],t[1])}),this):t&&Object.getOwnPropertyNames(t).forEach((function(e){this.append(e,t[e])}),this)}function d(t){if(t.bodyUsed)return Promise.reject(new TypeError("Already read"));t.bodyUsed=!0}function p(t){return new Promise((function(e,r){t.onload=function(){e(t.result)},t.onerror=function(){r(t.error)}}))}function y(t){var e=new FileReader,r=p(e);return e.readAsArrayBuffer(t),r}function b(t){if(t.slice)return t.slice(0);var e=new Uint8Array(t.byteLength);return e.set(new Uint8Array(t)),e.buffer}function m(){return this.bodyUsed=!1,this._initBody=function(t){var e;this._bodyInit=t,t?"string"==typeof t?this._bodyText=t:o&&Blob.prototype.isPrototypeOf(t)?this._bodyBlob=t:i&&FormData.prototype.isPrototypeOf(t)?this._bodyFormData=t:r&&URLSearchParams.prototype.isPrototypeOf(t)?this._bodyText=t.toString():s&&o&&(e=t)&&DataView.prototype.isPrototypeOf(e)?(this._bodyArrayBuffer=b(t.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):s&&(ArrayBuffer.prototype.isPrototypeOf(t)||c(t))?this._bodyArrayBuffer=b(t):this._bodyText=t=Object.prototype.toString.call(t):this._bodyText="",this.headers.get("content-type")||("string"==typeof t?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):r&&URLSearchParams.prototype.isPrototypeOf(t)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},o&&(this.blob=function(){var t=d(this);if(t)return t;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?d(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(y)}),this.text=function(){var t,e,r,n=d(this);if(n)return n;if(this._bodyBlob)return t=this._bodyBlob,r=p(e=new FileReader),e.readAsText(t),r;if(this._bodyArrayBuffer)return Promise.resolve(function(t){for(var e=new Uint8Array(t),r=new Array(e.length),n=0;n<e.length;n++)r[n]=String.fromCharCode(e[n]);return r.join("")}(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},i&&(this.formData=function(){return this.text().then(E)}),this.json=function(){return this.text().then(JSON.parse)},this}f.prototype.append=function(t,e){t=h(t),e=l(e);var r=this.map[t];this.map[t]=r?r+", "+e:e},f.prototype.delete=function(t){delete this.map[h(t)]},f.prototype.get=function(t){return t=h(t),this.has(t)?this.map[t]:null},f.prototype.has=function(t){return this.map.hasOwnProperty(h(t))},f.prototype.set=function(t,e){this.map[h(t)]=l(e)},f.prototype.forEach=function(t,e){for(var r in this.map)this.map.hasOwnProperty(r)&&t.call(e,this.map[r],r,this)},f.prototype.keys=function(){var t=[];return this.forEach((function(e,r){t.push(r)})),u(t)},f.prototype.values=function(){var t=[];return this.forEach((function(e){t.push(e)})),u(t)},f.prototype.entries=function(){var t=[];return this.forEach((function(e,r){t.push([r,e])})),u(t)},n&&(f.prototype[Symbol.iterator]=f.prototype.entries);var v=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function w(t,e){var r,n,o=(e=e||{}).body;if(t instanceof w){if(t.bodyUsed)throw new TypeError("Already read");this.url=t.url,this.credentials=t.credentials,e.headers||(this.headers=new f(t.headers)),this.method=t.method,this.mode=t.mode,this.signal=t.signal,o||null==t._bodyInit||(o=t._bodyInit,t.bodyUsed=!0)}else this.url=String(t);if(this.credentials=e.credentials||this.credentials||"same-origin",!e.headers&&this.headers||(this.headers=new f(e.headers)),this.method=(n=(r=e.method||this.method||"GET").toUpperCase(),v.indexOf(n)>-1?n:r),this.mode=e.mode||this.mode||null,this.signal=e.signal||this.signal,this.referrer=null,("GET"===this.method||"HEAD"===this.method)&&o)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(o)}function E(t){var e=new FormData;return t.trim().split("&").forEach((function(t){if(t){var r=t.split("="),n=r.shift().replace(/\+/g," "),o=r.join("=").replace(/\+/g," ");e.append(decodeURIComponent(n),decodeURIComponent(o))}})),e}function A(t,e){e||(e={}),this.type="default",this.status=void 0===e.status?200:e.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in e?e.statusText:"OK",this.headers=new f(e.headers),this.url=e.url||"",this._initBody(t)}w.prototype.clone=function(){return new w(this,{body:this._bodyInit})},m.call(w.prototype),m.call(A.prototype),A.prototype.clone=function(){return new A(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new f(this.headers),url:this.url})},A.error=function(){var t=new A(null,{status:0,statusText:""});return t.type="error",t};var g=[301,302,303,307,308];A.redirect=function(t,e){if(-1===g.indexOf(e))throw new RangeError("Invalid status code");return new A(null,{status:e,headers:{location:t}})},e.DOMException=t.DOMException;try{new e.DOMException}catch(t){e.DOMException=function(t,e){this.message=t,this.name=e;var r=Error(t);this.stack=r.stack},e.DOMException.prototype=Object.create(Error.prototype),e.DOMException.prototype.constructor=e.DOMException}function U(t,r){return new Promise((function(n,i){var s=new w(t,r);if(s.signal&&s.signal.aborted)return i(new e.DOMException("Aborted","AbortError"));var a=new XMLHttpRequest;function c(){a.abort()}a.onload=function(){var t,e,r={status:a.status,statusText:a.statusText,headers:(t=a.getAllResponseHeaders()||"",e=new f,t.replace(/\r?\n[\t ]+/g," ").split(/\r?\n/).forEach((function(t){var r=t.split(":"),n=r.shift().trim();if(n){var o=r.join(":").trim();e.append(n,o)}})),e)};r.url="responseURL"in a?a.responseURL:r.headers.get("X-Request-URL");var o="response"in a?a.response:a.responseText;n(new A(o,r))},a.onerror=function(){i(new TypeError("Network request failed"))},a.ontimeout=function(){i(new TypeError("Network request failed"))},a.onabort=function(){i(new e.DOMException("Aborted","AbortError"))},a.open(s.method,s.url,!0),"include"===s.credentials?a.withCredentials=!0:"omit"===s.credentials&&(a.withCredentials=!1),"responseType"in a&&o&&(a.responseType="blob"),s.headers.forEach((function(t,e){a.setRequestHeader(e,t)})),s.signal&&(s.signal.addEventListener("abort",c),a.onreadystatechange=function(){4===a.readyState&&s.signal.removeEventListener("abort",c)}),a.send(void 0===s._bodyInit?null:s._bodyInit)}))}U.polyfill=!0,t.fetch||(t.fetch=U,t.Headers=f,t.Request=w,t.Response=A),e.Headers=f,e.Request=w,e.Response=A,e.fetch=U,Object.defineProperty(e,"__esModule",{value:!0})}({})}("undefined"!=typeof self?self:this)}},e={};function r(n){var o=e[n];if(void 0!==o)return o.exports;var i=e[n]={exports:{}};return t[n].call(i.exports,i,i.exports,r),i.exports}r.d=(t,e)=>{for(var n in e)r.o(e,n)&&!r.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:e[n]})},r.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})};var n={};return(()=>{"use strict";r.r(n),r.d(n,{HIRO_MAINNET_DEFAULT:()=>m,HIRO_MOCKNET_DEFAULT:()=>w,HIRO_TESTNET_DEFAULT:()=>v,StacksMainnet:()=>U,StacksMocknet:()=>O,StacksNetwork:()=>g,StacksNetworks:()=>E,StacksTestnet:()=>T,createApiKeyMiddleware:()=>d,createFetchFn:()=>p,fetchWrapper:()=>u,getFetchOptions:()=>h,hostMatches:()=>f,setFetchOptions:()=>l}),r(616);var t=Object.defineProperty,e=Object.getOwnPropertySymbols,o=Object.prototype.hasOwnProperty,i=Object.prototype.propertyIsEnumerable,s=(e,r,n)=>r in e?t(e,r,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[r]=n,a=(t,r)=>{for(var n in r||(r={}))o.call(r,n)&&s(t,n,r[n]);if(e)for(var n of e(r))i.call(r,n)&&s(t,n,r[n]);return t};const c={referrerPolicy:"origin"},h=()=>c,l=t=>Object.assign(c,t);async function u(t,e){const r={};return Object.assign(r,e,c),await fetch(t,r)}function f(t,e){return"string"==typeof e?e===t:e.exec(t)}function d({apiKey:t,host:e=/(.*)api(.*)\.stacks\.co$/i,httpHeader:r="x-api-key"}){return{pre:n=>{if(!f(new URL(n.url).host,e))return;const o=new Headers(n.init.headers);o.set(r,t),n.init.headers=o}}}function p(...t){const{fetchLib:e,middlewares:r}=function(t){let e=u,r=[];return t.length>0&&"function"==typeof t[0]&&(e=t.shift()),t.length>0&&(r=t),{fetchLib:e,middlewares:r}}(t);return async(t,n)=>{var o;let i={url:t,init:null!=n?n:{}};for(const t of r)if("function"==typeof t.pre){const r=await Promise.resolve(t.pre(a({fetch:e},i)));i=null!=r?r:i}let s=await e(i.url,i.init);for(const t of r)if("function"==typeof t.post){const r=await Promise.resolve(t.post({fetch:e,url:i.url,init:i.init,response:null!=(o=null==s?void 0:s.clone())?o:s}));s=null!=r?r:s}return s}}var y,b;!function(t){t[t.Testnet=2147483648]="Testnet",t[t.Mainnet=1]="Mainnet"}(y||(y={})),function(t){t[t.Mainnet=0]="Mainnet",t[t.Testnet=128]="Testnet"}(b||(b={}));const m="https://stacks-node-api.mainnet.stacks.co",v="https://stacks-node-api.testnet.stacks.co",w="http://localhost:3999",E=["mainnet","testnet"],A=class{constructor(t){var e;this.version=b.Mainnet,this.chainId=y.Mainnet,this.bnsLookupUrl="https://stacks-node-api.mainnet.stacks.co",this.broadcastEndpoint="/v2/transactions",this.transferFeeEstimateEndpoint="/v2/fees/transfer",this.transactionFeeEstimateEndpoint="/v2/fees/transaction",this.accountEndpoint="/v2/accounts",this.contractAbiEndpoint="/v2/contracts/interface",this.readOnlyFunctionCallEndpoint="/v2/contracts/call-read",this.isMainnet=()=>this.version===b.Mainnet,this.getBroadcastApiUrl=()=>`${this.coreApiUrl}${this.broadcastEndpoint}`,this.getTransferFeeEstimateApiUrl=()=>`${this.coreApiUrl}${this.transferFeeEstimateEndpoint}`,this.getTransactionFeeEstimateApiUrl=()=>`${this.coreApiUrl}${this.transactionFeeEstimateEndpoint}`,this.getAccountApiUrl=t=>`${this.coreApiUrl}${this.accountEndpoint}/${t}?proof=0`,this.getAbiApiUrl=(t,e)=>`${this.coreApiUrl}${this.contractAbiEndpoint}/${t}/${e}`,this.getReadOnlyFunctionCallApiUrl=(t,e,r)=>`${this.coreApiUrl}${this.readOnlyFunctionCallEndpoint}/${t}/${e}/${encodeURIComponent(r)}`,this.getInfoUrl=()=>`${this.coreApiUrl}/v2/info`,this.getBlockTimeInfoUrl=()=>`${this.coreApiUrl}/extended/v1/info/network_block_times`,this.getPoxInfoUrl=()=>`${this.coreApiUrl}/v2/pox`,this.getRewardsUrl=(t,e)=>{let r=`${this.coreApiUrl}/extended/v1/burnchain/rewards/${t}`;return e&&(r=`${r}?limit=${e.limit}&offset=${e.offset}`),r},this.getRewardsTotalUrl=t=>`${this.coreApiUrl}/extended/v1/burnchain/rewards/${t}/total`,this.getRewardHoldersUrl=(t,e)=>{let r=`${this.coreApiUrl}/extended/v1/burnchain/reward_slot_holders/${t}`;return e&&(r=`${r}?limit=${e.limit}&offset=${e.offset}`),r},this.getStackerInfoUrl=(t,e)=>`${this.coreApiUrl}${this.readOnlyFunctionCallEndpoint}\n ${t}/${e}/get-stacker-info`,this.coreApiUrl=t.url,this.fetchFn=null!=(e=t.fetchFn)?e:p()}getNameInfo(t){const e=`${this.bnsLookupUrl}/v1/names/${t}`;return this.fetchFn(e).then((t=>{if(404===t.status)throw new Error("Name not found");if(200!==t.status)throw new Error(`Bad response status: ${t.status}`);return t.json()})).then((t=>t.address?Object.assign({},t,{address:t.address}):t))}};let g=A;g.fromName=t=>{switch(t){case"mainnet":return new U;case"testnet":return new T;default:throw new Error(`Invalid network name provided. Must be one of the following: ${E.join(", ")}`)}},g.fromNameOrNetwork=t=>"string"!=typeof t&&"version"in t?t:A.fromName(t);class U extends g{constructor(t){var e;super({url:null!=(e=null==t?void 0:t.url)?e:m,fetchFn:null==t?void 0:t.fetchFn}),this.version=b.Mainnet,this.chainId=y.Mainnet}}class T extends g{constructor(t){var e;super({url:null!=(e=null==t?void 0:t.url)?e:v,fetchFn:null==t?void 0:t.fetchFn}),this.version=b.Testnet,this.chainId=y.Testnet}}class O extends g{constructor(t){var e;super({url:null!=(e=null==t?void 0:t.url)?e:w,fetchFn:null==t?void 0:t.fetchFn}),this.version=b.Testnet,this.chainId=y.Testnet}}})(),n})())); | ||
//# sourceMappingURL=index.js.map |
{ | ||
"name": "@stacks/network", | ||
"version": "4.0.3-beta.0", | ||
"version": "4.1.0", | ||
"description": "Library for Stacks network operations", | ||
@@ -43,3 +43,4 @@ "keywords": [ | ||
"dependencies": { | ||
"@stacks/common": "^4.0.3-beta.0" | ||
"@stacks/common": "^4.1.0", | ||
"cross-fetch": "^3.1.5" | ||
}, | ||
@@ -67,3 +68,3 @@ "devDependencies": { | ||
"unpkg": "dist/umd/index.js", | ||
"gitHead": "e65defc1a2bef36884bdcc2010763935955e2856" | ||
"gitHead": "d0ca86ec4547a21d7da7730a1074f410b3e85b2a" | ||
} |
@@ -13,3 +13,3 @@ # @stacks/network | ||
Creating a Stacks mainnet, testnet or mocknet network | ||
### Create a Stacks mainnet, testnet or mocknet network | ||
@@ -26,3 +26,3 @@ ```typescript | ||
Setting a custom node URL | ||
### Set a custom node URL | ||
@@ -33,3 +33,3 @@ ```typescript | ||
Check if network is mainnet | ||
### Check if network is mainnet | ||
@@ -40,3 +40,3 @@ ```typescript | ||
Example usage in transaction builder | ||
### Network usage in transaction building | ||
@@ -56,5 +56,56 @@ ```typescript | ||
Get various API URLs | ||
### Use the built-in API key middleware | ||
Some Stacks APIs make use API keys to provide less rate-limited plans. | ||
```typescript | ||
import { createApiKeyMiddleware, createFetchFn, StacksMainnet } from '@stacks/network'; | ||
import { broadcastResponse, getNonce, makeSTXTokenTransfer } from '@stacks/transactions'; | ||
const myApiMiddleware = createApiKeyMiddleware('example_e8e044a3_41d8b0fe_3dd3988ef302'); | ||
const myFetchFn = createFetchFn(apiMiddleware); // middlewares can be used to create a new fetch function | ||
const myMainnet = new StacksMainnet({ fetchFn: myFetchFn }); // the fetchFn options can be passed to a StacksNetwork to override the default fetch function | ||
const txOptions = { | ||
recipient: 'SP3FGQ8Z7JY9BWYZ5WM53E0M9NK7WHJF0691NZ159', | ||
amount: 12345n, | ||
senderKey: 'b244296d5907de9864c0b0d51f98a13c52890be0404e83f273144cd5b9960eed01', | ||
memo: 'some memo', | ||
anchorMode: AnchorMode.Any, | ||
network: myMainnet, // make sure to pass in the custom network object | ||
}; | ||
const transaction = await makeSTXTokenTransfer(txOptions); // fee-estimation will use the custom fetchFn | ||
const response = await broadcastResponse(transaction, myMainnet); // make sure to broadcast via the custom network object | ||
// stacks.js functions, which take a StacksNetwork object will use the custom fetchFn | ||
const nonce = await getNonce('SP3FGQ8Z7JY9BWYZ5WM53E0M9NK7WHJF0691NZ159', myMainnet); | ||
``` | ||
### Use custom middleware | ||
Middleware can be used to hook into network calls before sending a request or after receiving a response. | ||
```typescript | ||
import { createFetchFn, RequestContext, ResponseContext, StacksTestnet } from '@stacks/network'; | ||
import { broadcastResponse, getNonce, makeSTXTokenTransfer } from '@stacks/transactions'; | ||
const preMiddleware = (ctx: RequestContext) => { | ||
ctx.init.headers = new Headers(); | ||
ctx.init.headers.set('x-foo', 'bar'); // override headers and set new `x-foo` header | ||
}; | ||
const postMiddleware = (ctx: ResponseContext) => { | ||
console.log(await ctx.response.json()); // log response body as json | ||
}; | ||
const fetchFn = createFetchFn({ pre: preMiddleware, post: preMiddleware }); // a middleware can contain `pre`, `post`, or both | ||
const network = new StacksTestnet({ fetchFn }); | ||
// stacks.js functions, which take a StacksNetwork object will use the custom fetchFn | ||
const nonce = await getNonce('SP3FGQ8Z7JY9BWYZ5WM53E0M9NK7WHJF0691NZ159', network); | ||
``` | ||
### Get various API URLs | ||
```typescript | ||
const txBroadcastUrl = network.getBroadcastApiUrl(); | ||
@@ -61,0 +112,0 @@ |
148
src/index.ts
@@ -1,146 +0,2 @@ | ||
import { TransactionVersion, ChainID, fetchPrivate } from '@stacks/common'; | ||
export const HIRO_MAINNET_DEFAULT = 'https://stacks-node-api.mainnet.stacks.co'; | ||
export const HIRO_TESTNET_DEFAULT = 'https://stacks-node-api.testnet.stacks.co'; | ||
export const HIRO_MOCKNET_DEFAULT = 'http://localhost:3999'; | ||
export interface NetworkConfig { | ||
url: string; | ||
} | ||
export const StacksNetworks = ['mainnet', 'testnet'] as const; | ||
export type StacksNetworkName = typeof StacksNetworks[number]; | ||
export class StacksNetwork { | ||
version = TransactionVersion.Mainnet; | ||
chainId = ChainID.Mainnet; | ||
bnsLookupUrl = 'https://stacks-node-api.mainnet.stacks.co'; | ||
broadcastEndpoint = '/v2/transactions'; | ||
transferFeeEstimateEndpoint = '/v2/fees/transfer'; | ||
transactionFeeEstimateEndpoint = '/v2/fees/transaction'; | ||
accountEndpoint = '/v2/accounts'; | ||
contractAbiEndpoint = '/v2/contracts/interface'; | ||
readOnlyFunctionCallEndpoint = '/v2/contracts/call-read'; | ||
readonly coreApiUrl: string; | ||
constructor(networkConfig: NetworkConfig) { | ||
this.coreApiUrl = networkConfig.url; | ||
} | ||
static fromName = (networkName: StacksNetworkName): StacksNetwork => { | ||
switch (networkName) { | ||
case 'mainnet': | ||
return new StacksMainnet(); | ||
case 'testnet': | ||
return new StacksTestnet(); | ||
default: | ||
throw new Error( | ||
`Invalid network name provided. Must be one of the following: ${StacksNetworks.join( | ||
', ' | ||
)}` | ||
); | ||
} | ||
}; | ||
static fromNameOrNetwork = (network: StacksNetworkName | StacksNetwork) => { | ||
if (typeof network !== 'string' && 'version' in network) { | ||
return network; | ||
} | ||
return StacksNetwork.fromName(network); | ||
}; | ||
isMainnet = () => this.version === TransactionVersion.Mainnet; | ||
getBroadcastApiUrl = () => `${this.coreApiUrl}${this.broadcastEndpoint}`; | ||
getTransferFeeEstimateApiUrl = () => `${this.coreApiUrl}${this.transferFeeEstimateEndpoint}`; | ||
getTransactionFeeEstimateApiUrl = () => | ||
`${this.coreApiUrl}${this.transactionFeeEstimateEndpoint}`; | ||
getAccountApiUrl = (address: string) => | ||
`${this.coreApiUrl}${this.accountEndpoint}/${address}?proof=0`; | ||
getAbiApiUrl = (address: string, contract: string) => | ||
`${this.coreApiUrl}${this.contractAbiEndpoint}/${address}/${contract}`; | ||
getReadOnlyFunctionCallApiUrl = ( | ||
contractAddress: string, | ||
contractName: string, | ||
functionName: string | ||
) => | ||
`${this.coreApiUrl}${ | ||
this.readOnlyFunctionCallEndpoint | ||
}/${contractAddress}/${contractName}/${encodeURIComponent(functionName)}`; | ||
getInfoUrl = () => `${this.coreApiUrl}/v2/info`; | ||
getBlockTimeInfoUrl = () => `${this.coreApiUrl}/extended/v1/info/network_block_times`; | ||
getPoxInfoUrl = () => `${this.coreApiUrl}/v2/pox`; | ||
getRewardsUrl = (address: string, options?: any) => { | ||
let url = `${this.coreApiUrl}/extended/v1/burnchain/rewards/${address}`; | ||
if (options) { | ||
url = `${url}?limit=${options.limit}&offset=${options.offset}`; | ||
} | ||
return url; | ||
}; | ||
getRewardsTotalUrl = (address: string) => | ||
`${this.coreApiUrl}/extended/v1/burnchain/rewards/${address}/total`; | ||
getRewardHoldersUrl = (address: string, options?: any) => { | ||
let url = `${this.coreApiUrl}/extended/v1/burnchain/reward_slot_holders/${address}`; | ||
if (options) { | ||
url = `${url}?limit=${options.limit}&offset=${options.offset}`; | ||
} | ||
return url; | ||
}; | ||
getStackerInfoUrl = (contractAddress: string, contractName: string) => | ||
`${this.coreApiUrl}${this.readOnlyFunctionCallEndpoint} | ||
${contractAddress}/${contractName}/get-stacker-info`; | ||
getNameInfo(fullyQualifiedName: string) { | ||
/* | ||
TODO: Update to v2 API URL for name lookups | ||
*/ | ||
const nameLookupURL = `${this.bnsLookupUrl}/v1/names/${fullyQualifiedName}`; | ||
return fetchPrivate(nameLookupURL) | ||
.then(resp => { | ||
if (resp.status === 404) { | ||
throw new Error('Name not found'); | ||
} else if (resp.status !== 200) { | ||
throw new Error(`Bad response status: ${resp.status}`); | ||
} else { | ||
return resp.json(); | ||
} | ||
}) | ||
.then(nameInfo => { | ||
// the returned address _should_ be in the correct network --- | ||
// blockstackd gets into trouble because it tries to coerce back to mainnet | ||
// and the regtest transaction generation libraries want to use testnet addresses | ||
if (nameInfo.address) { | ||
return Object.assign({}, nameInfo, { address: nameInfo.address }); | ||
} else { | ||
return nameInfo; | ||
} | ||
}); | ||
} | ||
} | ||
export class StacksMainnet extends StacksNetwork { | ||
version = TransactionVersion.Mainnet; | ||
chainId = ChainID.Mainnet; | ||
constructor(networkUrl: NetworkConfig = { url: HIRO_MAINNET_DEFAULT }) { | ||
super(networkUrl); | ||
} | ||
} | ||
export class StacksTestnet extends StacksNetwork { | ||
version = TransactionVersion.Testnet; | ||
chainId = ChainID.Testnet; | ||
constructor(networkUrl: NetworkConfig = { url: HIRO_TESTNET_DEFAULT }) { | ||
super(networkUrl); | ||
} | ||
} | ||
export class StacksMocknet extends StacksNetwork { | ||
version = TransactionVersion.Testnet; | ||
chainId = ChainID.Testnet; | ||
constructor(networkUrl: NetworkConfig = { url: HIRO_MOCKNET_DEFAULT }) { | ||
super(networkUrl); | ||
} | ||
} | ||
export * from './fetch'; | ||
export * from './network'; |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
No v1
QualityPackage is not semver >=1. This means it is not stable and does not support ^ ranges.
Found 1 instance in 1 package
132508
27
1019
0
129
2
5
+ Addedcross-fetch@^3.1.5
+ Addedcross-fetch@3.2.0(transitive)
+ Addednode-fetch@2.7.0(transitive)
+ Addedtr46@0.0.3(transitive)
+ Addedwebidl-conversions@3.0.1(transitive)
+ Addedwhatwg-url@5.0.0(transitive)
Updated@stacks/common@^4.1.0