@stacks/network
Advanced tools
Comparing version 6.14.0-beta.0 to 6.14.1-next.31
@@ -1,2 +0,2 @@ | ||
export * from './fetch'; | ||
export * from './constants'; | ||
export * from './network'; |
@@ -1,3 +0,3 @@ | ||
export * from './fetch'; | ||
export * from './constants'; | ||
export * from './network'; | ||
//# sourceMappingURL=index.js.map |
@@ -1,61 +0,15 @@ | ||
import { TransactionVersion, ChainID } from '@stacks/common'; | ||
import { FetchFn } from './fetch'; | ||
export declare const HIRO_MAINNET_DEFAULT = "https://api.mainnet.hiro.so"; | ||
export declare const HIRO_TESTNET_DEFAULT = "https://api.testnet.hiro.so"; | ||
export declare const HIRO_MOCKNET_DEFAULT = "http://localhost:3999"; | ||
export interface NetworkConfig { | ||
url: string; | ||
fetchFn?: FetchFn; | ||
export interface StacksNetwork { | ||
chainId: number; | ||
transactionVersion: number; | ||
peerNetworkId: number; | ||
magicBytes: string; | ||
} | ||
export declare const STACKS_MAINNET: StacksNetwork; | ||
export declare const STACKS_TESTNET: StacksNetwork; | ||
export declare const STACKS_DEVNET: StacksNetwork; | ||
export declare const STACKS_MOCKNET: StacksNetwork; | ||
export declare const StacksNetworks: readonly ["mainnet", "testnet", "devnet", "mocknet"]; | ||
export 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; | ||
fetchFn: FetchFn; | ||
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; | ||
getAccountExtendedBalancesApiUrl: (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; | ||
getDataVarUrl: (contractAddress: string, contractName: string, dataVarName: string) => string; | ||
getMapEntryUrl: (contractAddress: string, contractName: string, mapName: string) => string; | ||
getNameInfo(fullyQualifiedName: string): Promise<any>; | ||
} | ||
export declare class StacksMainnet extends StacksNetwork { | ||
version: TransactionVersion; | ||
chainId: ChainID; | ||
constructor(opts?: Partial<NetworkConfig>); | ||
} | ||
export declare class StacksTestnet extends StacksNetwork { | ||
version: TransactionVersion; | ||
chainId: ChainID; | ||
constructor(opts?: Partial<NetworkConfig>); | ||
} | ||
export declare class StacksMocknet extends StacksNetwork { | ||
version: TransactionVersion; | ||
chainId: ChainID; | ||
constructor(opts?: Partial<NetworkConfig>); | ||
} | ||
export declare const StacksDevnet: typeof StacksMocknet; | ||
export declare function networkFromName(name: StacksNetworkName): StacksNetwork; | ||
export declare function networkFrom(network: StacksNetworkName | StacksNetwork): StacksNetwork; | ||
export declare function deriveDefaultUrl(network: StacksNetwork | StacksNetworkName | undefined): "https://api.mainnet.hiro.so" | "http://localhost:3999" | "https://api.testnet.hiro.so"; |
@@ -1,126 +0,50 @@ | ||
import { TransactionVersion, ChainID } from '@stacks/common'; | ||
import { createFetchFn } from './fetch'; | ||
export const HIRO_MAINNET_DEFAULT = 'https://api.mainnet.hiro.so'; | ||
export const HIRO_TESTNET_DEFAULT = 'https://api.testnet.hiro.so'; | ||
export const HIRO_MOCKNET_DEFAULT = 'http://localhost:3999'; | ||
import { DEVNET_URL, HIRO_MAINNET_URL, HIRO_TESTNET_URL } from '@stacks/common'; | ||
import { ChainId, PeerNetworkId, TransactionVersion } from './constants'; | ||
export const STACKS_MAINNET = { | ||
chainId: ChainId.Mainnet, | ||
transactionVersion: TransactionVersion.Mainnet, | ||
peerNetworkId: PeerNetworkId.Mainnet, | ||
magicBytes: 'X2', | ||
}; | ||
export const STACKS_TESTNET = { | ||
chainId: ChainId.Testnet, | ||
transactionVersion: TransactionVersion.Testnet, | ||
peerNetworkId: PeerNetworkId.Testnet, | ||
magicBytes: 'T2', | ||
}; | ||
export const STACKS_DEVNET = { | ||
...STACKS_TESTNET, | ||
magicBytes: 'id', | ||
}; | ||
export const STACKS_MOCKNET = { ...STACKS_DEVNET }; | ||
export const StacksNetworks = ['mainnet', 'testnet', 'devnet', 'mocknet']; | ||
export class StacksNetwork { | ||
constructor(networkConfig) { | ||
this.version = TransactionVersion.Mainnet; | ||
this.chainId = ChainID.Mainnet; | ||
this.bnsLookupUrl = 'https://api.mainnet.hiro.so'; | ||
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.getAccountExtendedBalancesApiUrl = (address) => `${this.coreApiUrl}/extended/v1/address/${address}/balances`; | ||
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.getDataVarUrl = (contractAddress, contractName, dataVarName) => `${this.coreApiUrl}/v2/data_var/${contractAddress}/${contractName}/${dataVarName}?proof=0`; | ||
this.getMapEntryUrl = (contractAddress, contractName, mapName) => `${this.coreApiUrl}/v2/map_entry/${contractAddress}/${contractName}/${mapName}?proof=0`; | ||
this.coreApiUrl = networkConfig.url; | ||
this.fetchFn = networkConfig.fetchFn ?? createFetchFn(); | ||
} | ||
getNameInfo(fullyQualifiedName) { | ||
const nameLookupURL = `${this.bnsLookupUrl}/v1/names/${fullyQualifiedName}`; | ||
return this.fetchFn(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) { | ||
export function networkFromName(name) { | ||
switch (name) { | ||
case 'mainnet': | ||
return new StacksMainnet(); | ||
return STACKS_MAINNET; | ||
case 'testnet': | ||
return new StacksTestnet(); | ||
return STACKS_TESTNET; | ||
case 'devnet': | ||
return new StacksDevnet(); | ||
return STACKS_DEVNET; | ||
case 'mocknet': | ||
return new StacksMocknet(); | ||
return STACKS_MOCKNET; | ||
default: | ||
throw new Error(`Invalid network name provided. Must be one of the following: ${StacksNetworks.join(', ')}`); | ||
throw new Error(`Unknown network name: ${name}`); | ||
} | ||
}; | ||
StacksNetwork.fromNameOrNetwork = (network) => { | ||
if (typeof network !== 'string' && 'version' in network) { | ||
return network; | ||
} | ||
return StacksNetwork.fromName(network); | ||
}; | ||
export class StacksMainnet extends StacksNetwork { | ||
constructor(opts) { | ||
super({ | ||
url: opts?.url ?? HIRO_MAINNET_DEFAULT, | ||
fetchFn: opts?.fetchFn, | ||
}); | ||
this.version = TransactionVersion.Mainnet; | ||
this.chainId = ChainID.Mainnet; | ||
} | ||
} | ||
export class StacksTestnet extends StacksNetwork { | ||
constructor(opts) { | ||
super({ | ||
url: opts?.url ?? HIRO_TESTNET_DEFAULT, | ||
fetchFn: opts?.fetchFn, | ||
}); | ||
this.version = TransactionVersion.Testnet; | ||
this.chainId = ChainID.Testnet; | ||
} | ||
export function networkFrom(network) { | ||
if (typeof network === 'string') | ||
return networkFromName(network); | ||
return network; | ||
} | ||
export class StacksMocknet extends StacksNetwork { | ||
constructor(opts) { | ||
super({ | ||
url: opts?.url ?? HIRO_MOCKNET_DEFAULT, | ||
fetchFn: opts?.fetchFn, | ||
}); | ||
this.version = TransactionVersion.Testnet; | ||
this.chainId = ChainID.Testnet; | ||
} | ||
export function deriveDefaultUrl(network) { | ||
if (!network) | ||
return HIRO_MAINNET_URL; | ||
network = networkFrom(network); | ||
return !network || network.transactionVersion === TransactionVersion.Mainnet | ||
? HIRO_MAINNET_URL | ||
: network.magicBytes === 'id' | ||
? DEVNET_URL | ||
: HIRO_TESTNET_URL; | ||
} | ||
export const StacksDevnet = StacksMocknet; | ||
//# sourceMappingURL=network.js.map |
@@ -1,2 +0,2 @@ | ||
export * from './fetch'; | ||
export * from './constants'; | ||
export * from './network'; |
@@ -17,4 +17,4 @@ "use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
__exportStar(require("./fetch"), exports); | ||
__exportStar(require("./constants"), exports); | ||
__exportStar(require("./network"), exports); | ||
//# sourceMappingURL=index.js.map |
@@ -1,61 +0,15 @@ | ||
import { TransactionVersion, ChainID } from '@stacks/common'; | ||
import { FetchFn } from './fetch'; | ||
export declare const HIRO_MAINNET_DEFAULT = "https://api.mainnet.hiro.so"; | ||
export declare const HIRO_TESTNET_DEFAULT = "https://api.testnet.hiro.so"; | ||
export declare const HIRO_MOCKNET_DEFAULT = "http://localhost:3999"; | ||
export interface NetworkConfig { | ||
url: string; | ||
fetchFn?: FetchFn; | ||
export interface StacksNetwork { | ||
chainId: number; | ||
transactionVersion: number; | ||
peerNetworkId: number; | ||
magicBytes: string; | ||
} | ||
export declare const STACKS_MAINNET: StacksNetwork; | ||
export declare const STACKS_TESTNET: StacksNetwork; | ||
export declare const STACKS_DEVNET: StacksNetwork; | ||
export declare const STACKS_MOCKNET: StacksNetwork; | ||
export declare const StacksNetworks: readonly ["mainnet", "testnet", "devnet", "mocknet"]; | ||
export 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; | ||
fetchFn: FetchFn; | ||
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; | ||
getAccountExtendedBalancesApiUrl: (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; | ||
getDataVarUrl: (contractAddress: string, contractName: string, dataVarName: string) => string; | ||
getMapEntryUrl: (contractAddress: string, contractName: string, mapName: string) => string; | ||
getNameInfo(fullyQualifiedName: string): Promise<any>; | ||
} | ||
export declare class StacksMainnet extends StacksNetwork { | ||
version: TransactionVersion; | ||
chainId: ChainID; | ||
constructor(opts?: Partial<NetworkConfig>); | ||
} | ||
export declare class StacksTestnet extends StacksNetwork { | ||
version: TransactionVersion; | ||
chainId: ChainID; | ||
constructor(opts?: Partial<NetworkConfig>); | ||
} | ||
export declare class StacksMocknet extends StacksNetwork { | ||
version: TransactionVersion; | ||
chainId: ChainID; | ||
constructor(opts?: Partial<NetworkConfig>); | ||
} | ||
export declare const StacksDevnet: typeof StacksMocknet; | ||
export declare function networkFromName(name: StacksNetworkName): StacksNetwork; | ||
export declare function networkFrom(network: StacksNetworkName | StacksNetwork): StacksNetwork; | ||
export declare function deriveDefaultUrl(network: StacksNetwork | StacksNetworkName | undefined): "https://api.mainnet.hiro.so" | "http://localhost:3999" | "https://api.testnet.hiro.so"; |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.StacksDevnet = exports.StacksMocknet = exports.StacksTestnet = exports.StacksMainnet = exports.StacksNetwork = exports.StacksNetworks = exports.HIRO_MOCKNET_DEFAULT = exports.HIRO_TESTNET_DEFAULT = exports.HIRO_MAINNET_DEFAULT = void 0; | ||
exports.deriveDefaultUrl = exports.networkFrom = exports.networkFromName = exports.StacksNetworks = exports.STACKS_MOCKNET = exports.STACKS_DEVNET = exports.STACKS_TESTNET = exports.STACKS_MAINNET = void 0; | ||
const common_1 = require("@stacks/common"); | ||
const fetch_1 = require("./fetch"); | ||
exports.HIRO_MAINNET_DEFAULT = 'https://api.mainnet.hiro.so'; | ||
exports.HIRO_TESTNET_DEFAULT = 'https://api.testnet.hiro.so'; | ||
exports.HIRO_MOCKNET_DEFAULT = 'http://localhost:3999'; | ||
const constants_1 = require("./constants"); | ||
exports.STACKS_MAINNET = { | ||
chainId: constants_1.ChainId.Mainnet, | ||
transactionVersion: constants_1.TransactionVersion.Mainnet, | ||
peerNetworkId: constants_1.PeerNetworkId.Mainnet, | ||
magicBytes: 'X2', | ||
}; | ||
exports.STACKS_TESTNET = { | ||
chainId: constants_1.ChainId.Testnet, | ||
transactionVersion: constants_1.TransactionVersion.Testnet, | ||
peerNetworkId: constants_1.PeerNetworkId.Testnet, | ||
magicBytes: 'T2', | ||
}; | ||
exports.STACKS_DEVNET = { | ||
...exports.STACKS_TESTNET, | ||
magicBytes: 'id', | ||
}; | ||
exports.STACKS_MOCKNET = { ...exports.STACKS_DEVNET }; | ||
exports.StacksNetworks = ['mainnet', 'testnet', 'devnet', 'mocknet']; | ||
class StacksNetwork { | ||
constructor(networkConfig) { | ||
this.version = common_1.TransactionVersion.Mainnet; | ||
this.chainId = common_1.ChainID.Mainnet; | ||
this.bnsLookupUrl = 'https://api.mainnet.hiro.so'; | ||
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.getAccountExtendedBalancesApiUrl = (address) => `${this.coreApiUrl}/extended/v1/address/${address}/balances`; | ||
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.getDataVarUrl = (contractAddress, contractName, dataVarName) => `${this.coreApiUrl}/v2/data_var/${contractAddress}/${contractName}/${dataVarName}?proof=0`; | ||
this.getMapEntryUrl = (contractAddress, contractName, mapName) => `${this.coreApiUrl}/v2/map_entry/${contractAddress}/${contractName}/${mapName}?proof=0`; | ||
this.coreApiUrl = networkConfig.url; | ||
this.fetchFn = networkConfig.fetchFn ?? (0, fetch_1.createFetchFn)(); | ||
} | ||
getNameInfo(fullyQualifiedName) { | ||
const nameLookupURL = `${this.bnsLookupUrl}/v1/names/${fullyQualifiedName}`; | ||
return this.fetchFn(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) { | ||
function networkFromName(name) { | ||
switch (name) { | ||
case 'mainnet': | ||
return new StacksMainnet(); | ||
return exports.STACKS_MAINNET; | ||
case 'testnet': | ||
return new StacksTestnet(); | ||
return exports.STACKS_TESTNET; | ||
case 'devnet': | ||
return new exports.StacksDevnet(); | ||
return exports.STACKS_DEVNET; | ||
case 'mocknet': | ||
return new StacksMocknet(); | ||
return exports.STACKS_MOCKNET; | ||
default: | ||
throw new Error(`Invalid network name provided. Must be one of the following: ${exports.StacksNetworks.join(', ')}`); | ||
throw new Error(`Unknown network name: ${name}`); | ||
} | ||
}; | ||
StacksNetwork.fromNameOrNetwork = (network) => { | ||
if (typeof network !== 'string' && 'version' in network) { | ||
return network; | ||
} | ||
return StacksNetwork.fromName(network); | ||
}; | ||
class StacksMainnet extends StacksNetwork { | ||
constructor(opts) { | ||
super({ | ||
url: opts?.url ?? exports.HIRO_MAINNET_DEFAULT, | ||
fetchFn: opts?.fetchFn, | ||
}); | ||
this.version = common_1.TransactionVersion.Mainnet; | ||
this.chainId = common_1.ChainID.Mainnet; | ||
} | ||
} | ||
exports.StacksMainnet = StacksMainnet; | ||
class StacksTestnet extends StacksNetwork { | ||
constructor(opts) { | ||
super({ | ||
url: opts?.url ?? exports.HIRO_TESTNET_DEFAULT, | ||
fetchFn: opts?.fetchFn, | ||
}); | ||
this.version = common_1.TransactionVersion.Testnet; | ||
this.chainId = common_1.ChainID.Testnet; | ||
} | ||
exports.networkFromName = networkFromName; | ||
function networkFrom(network) { | ||
if (typeof network === 'string') | ||
return networkFromName(network); | ||
return network; | ||
} | ||
exports.StacksTestnet = StacksTestnet; | ||
class StacksMocknet extends StacksNetwork { | ||
constructor(opts) { | ||
super({ | ||
url: opts?.url ?? exports.HIRO_MOCKNET_DEFAULT, | ||
fetchFn: opts?.fetchFn, | ||
}); | ||
this.version = common_1.TransactionVersion.Testnet; | ||
this.chainId = common_1.ChainID.Testnet; | ||
} | ||
exports.networkFrom = networkFrom; | ||
function deriveDefaultUrl(network) { | ||
if (!network) | ||
return common_1.HIRO_MAINNET_URL; | ||
network = networkFrom(network); | ||
return !network || network.transactionVersion === constants_1.TransactionVersion.Mainnet | ||
? common_1.HIRO_MAINNET_URL | ||
: network.magicBytes === 'id' | ||
? common_1.DEVNET_URL | ||
: common_1.HIRO_TESTNET_URL; | ||
} | ||
exports.StacksMocknet = StacksMocknet; | ||
exports.StacksDevnet = StacksMocknet; | ||
exports.deriveDefaultUrl = deriveDefaultUrl; | ||
//# sourceMappingURL=network.js.map |
@@ -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 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 d(t){this.map={},t instanceof d?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)||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=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,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}d.prototype.append=function(t,e){t=h(t),e=l(e);var r=this.map[t];this.map[t]=r?r+", "+e:e},d.prototype.delete=function(t){delete this.map[h(t)]},d.prototype.get=function(t){return t=h(t),this.has(t)?this.map[t]:null},d.prototype.has=function(t){return this.map.hasOwnProperty(h(t))},d.prototype.set=function(t,e){this.map[h(t)]=l(e)},d.prototype.forEach=function(t,e){for(var r in this.map)this.map.hasOwnProperty(r)&&t.call(e,this.map[r],r,this)},d.prototype.keys=function(){var t=[];return this.forEach((function(e,r){t.push(r)})),u(t)},d.prototype.values=function(){var t=[];return this.forEach((function(e){t.push(e)})),u(t)},d.prototype.entries=function(){var t=[];return this.forEach((function(e,r){t.push([r,e])})),u(t)},n&&(d.prototype[Symbol.iterator]=d.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 d(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 d(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 d(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 d(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 d,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=d,t.Request=w,t.Response=A),e.Headers=d,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:()=>v,HIRO_MOCKNET_DEFAULT:()=>E,HIRO_TESTNET_DEFAULT:()=>w,StacksDevnet:()=>_,StacksMainnet:()=>T,StacksMocknet:()=>O,StacksNetwork:()=>U,StacksNetworks:()=>A,StacksTestnet:()=>x,createApiKeyMiddleware:()=>f,createFetchFn:()=>p,fetchWrapper:()=>u,getFetchOptions:()=>h,hostMatches:()=>d,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",headers:{"x-hiro-product":"stacksjs"}},h=()=>c,l=t=>Object.assign(c,t);async function u(t,e){const r={};return Object.assign(r,c,e),await fetch(t,r)}function d(t,e){return"string"==typeof e?e===t:e.exec(t)}function f({apiKey:t,host:e=/(.*)api(.*)(\.stacks\.co|\.hiro\.so)$/i,httpHeader:r="x-api-key"}){return{pre:n=>{if(!d(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,m;!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={})),function(t){t[t.Mainnet=385875968]="Mainnet",t[t.Testnet=4278190080]="Testnet"}(m||(m={}));const v="https://api.mainnet.hiro.so",w="https://api.testnet.hiro.so",E="http://localhost:3999",A=["mainnet","testnet","devnet","mocknet"],g=class{constructor(t){var e;this.version=b.Mainnet,this.chainId=y.Mainnet,this.bnsLookupUrl="https://api.mainnet.hiro.so",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.getAccountExtendedBalancesApiUrl=t=>`${this.coreApiUrl}/extended/v1/address/${t}/balances`,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.getDataVarUrl=(t,e,r)=>`${this.coreApiUrl}/v2/data_var/${t}/${e}/${r}?proof=0`,this.getMapEntryUrl=(t,e,r)=>`${this.coreApiUrl}/v2/map_entry/${t}/${e}/${r}?proof=0`,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))}};g.fromName=t=>{switch(t){case"mainnet":return new T;case"testnet":return new x;case"devnet":return new _;case"mocknet":return new O;default:throw new Error(`Invalid network name provided. Must be one of the following: ${A.join(", ")}`)}},g.fromNameOrNetwork=t=>"string"!=typeof t&&"version"in t?t:g.fromName(t);let U=g;class T extends U{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.Mainnet,this.chainId=y.Mainnet}}class x extends U{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}}class O extends U{constructor(t){var e;super({url:null!=(e=null==t?void 0:t.url)?e:E,fetchFn:null==t?void 0:t.fetchFn}),this.version=b.Testnet,this.chainId=y.Testnet}}const _=O})(),n})())); | ||
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.StacksNetwork=t():e.StacksNetwork=t()}(this,(()=>(()=>{"use strict";var e={d:(t,n)=>{for(var r in n)e.o(n,r)&&!e.o(t,r)&&Object.defineProperty(t,r,{enumerable:!0,get:n[r]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.r(t),e.d(t,{ChainId:()=>n,DEFAULT_CHAIN_ID:()=>o,DEFAULT_TRANSACTION_VERSION:()=>i,PeerNetworkId:()=>r,STACKS_DEVNET:()=>N,STACKS_MAINNET:()=>w,STACKS_MOCKNET:()=>h,STACKS_TESTNET:()=>O,StacksNetworks:()=>k,TransactionVersion:()=>a,deriveDefaultUrl:()=>j,networkFrom:()=>g,networkFromName:()=>M,whenTransactionVersion:()=>s});var n=(e=>(e[e.Mainnet=1]="Mainnet",e[e.Testnet=2147483648]="Testnet",e))(n||{}),r=(e=>(e[e.Mainnet=385875968]="Mainnet",e[e.Testnet=4278190080]="Testnet",e))(r||{});const o=1;var a=(e=>(e[e.Mainnet=0]="Mainnet",e[e.Testnet=128]="Testnet",e))(a||{});const i=0;function s(e){return t=>t[e]}const c="https://api.mainnet.hiro.so",p="https://api.testnet.hiro.so",u="http://localhost:3999";var d=Object.defineProperty,f=Object.defineProperties,T=Object.getOwnPropertyDescriptors,l=Object.getOwnPropertySymbols,y=Object.prototype.hasOwnProperty,m=Object.prototype.propertyIsEnumerable,b=(e,t,n)=>t in e?d(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,S=(e,t)=>{for(var n in t||(t={}))y.call(t,n)&&b(e,n,t[n]);if(l)for(var n of l(t))m.call(t,n)&&b(e,n,t[n]);return e};const w={chainId:n.Mainnet,transactionVersion:a.Mainnet,peerNetworkId:r.Mainnet,magicBytes:"X2"},O={chainId:n.Testnet,transactionVersion:a.Testnet,peerNetworkId:r.Testnet,magicBytes:"T2"},N=f(S({},O),T({magicBytes:"id"}));const h=S({},N),k=["mainnet","testnet","devnet","mocknet"];function M(e){switch(e){case"mainnet":return w;case"testnet":return O;case"devnet":return N;case"mocknet":return h;default:throw new Error(`Unknown network name: ${e}`)}}function g(e){return"string"==typeof e?M(e):e}function j(e){return e&&(e=g(e))&&e.transactionVersion!==a.Mainnet?"id"===e.magicBytes?u:p:c}return t})())); | ||
//# sourceMappingURL=index.js.map |
{ | ||
"name": "@stacks/network", | ||
"version": "6.14.0-beta.0", | ||
"version": "6.14.1-next.31+e618d2f3", | ||
"description": "Library for Stacks network operations", | ||
@@ -23,3 +23,3 @@ "license": "MIT", | ||
"dependencies": { | ||
"@stacks/common": "^6.14.0-beta.0", | ||
"@stacks/common": "^6.14.1-next.31+e618d2f3", | ||
"cross-fetch": "^3.1.5" | ||
@@ -56,3 +56,3 @@ }, | ||
}, | ||
"gitHead": "a91f28c64f6201435ee8c7ca328c6c5100ab2f0a" | ||
"gitHead": "e618d2f38d09bddd441311db9fa6cc549f702c4e" | ||
} |
@@ -1,2 +0,2 @@ | ||
export * from './fetch'; | ||
export * from './constants'; | ||
export * from './network'; |
@@ -1,19 +0,32 @@ | ||
import { TransactionVersion, ChainID } from '@stacks/common'; | ||
import { createFetchFn, FetchFn } from './fetch'; | ||
import { DEVNET_URL, HIRO_MAINNET_URL, HIRO_TESTNET_URL } from '@stacks/common'; | ||
import { ChainId, PeerNetworkId, TransactionVersion } from './constants'; | ||
export const HIRO_MAINNET_DEFAULT = 'https://api.mainnet.hiro.so'; | ||
export const HIRO_TESTNET_DEFAULT = 'https://api.testnet.hiro.so'; | ||
export const HIRO_MOCKNET_DEFAULT = 'http://localhost:3999'; | ||
/** | ||
* Used for constructing Network instances | ||
* @related {@link StacksNetwork}, {@link StacksMainnet}, {@link StacksTestnet}, {@link StacksDevnet}, {@link StacksMocknet} | ||
*/ | ||
export interface NetworkConfig { | ||
/** The base API/node URL for the network fetch calls */ | ||
url: string; | ||
/** An optional custom fetch function to override default behaviors */ | ||
fetchFn?: FetchFn; | ||
export interface StacksNetwork { | ||
chainId: number; | ||
transactionVersion: number; // todo: txVersion better? | ||
peerNetworkId: number; | ||
magicBytes: string; | ||
// todo: add check32 character bytes string | ||
} | ||
export const STACKS_MAINNET: StacksNetwork = { | ||
chainId: ChainId.Mainnet, | ||
transactionVersion: TransactionVersion.Mainnet, | ||
peerNetworkId: PeerNetworkId.Mainnet, | ||
magicBytes: 'X2', // todo: comment bytes version of magic bytes | ||
}; | ||
export const STACKS_TESTNET: StacksNetwork = { | ||
chainId: ChainId.Testnet, | ||
transactionVersion: TransactionVersion.Testnet, | ||
peerNetworkId: PeerNetworkId.Testnet, | ||
magicBytes: 'T2', // todo: comment bytes version of magic bytes | ||
}; | ||
export const STACKS_DEVNET: StacksNetwork = { | ||
...STACKS_TESTNET, | ||
magicBytes: 'id', // todo: comment bytes version of magic bytes | ||
}; | ||
export const STACKS_MOCKNET: StacksNetwork = { ...STACKS_DEVNET }; | ||
/** @ignore internal */ | ||
@@ -24,193 +37,32 @@ export const StacksNetworks = ['mainnet', 'testnet', 'devnet', 'mocknet'] as const; | ||
/** | ||
* The base class for Stacks networks. Typically used via its subclasses. | ||
* @related {@link StacksMainnet}, {@link StacksTestnet}, {@link StacksDevnet}, {@link StacksMocknet} | ||
*/ | ||
export class StacksNetwork { | ||
version: TransactionVersion = TransactionVersion.Mainnet; | ||
chainId: ChainID = ChainID.Mainnet; | ||
bnsLookupUrl = 'https://api.mainnet.hiro.so'; | ||
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; | ||
fetchFn: FetchFn; | ||
constructor(networkConfig: NetworkConfig) { | ||
this.coreApiUrl = networkConfig.url; | ||
this.fetchFn = networkConfig.fetchFn ?? createFetchFn(); | ||
export function networkFromName(name: StacksNetworkName) { | ||
switch (name) { | ||
case 'mainnet': | ||
return STACKS_MAINNET; | ||
case 'testnet': | ||
return STACKS_TESTNET; | ||
case 'devnet': | ||
return STACKS_DEVNET; | ||
case 'mocknet': | ||
return STACKS_MOCKNET; | ||
default: | ||
throw new Error(`Unknown network name: ${name}`); | ||
} | ||
/** A static network constructor from a network name */ | ||
static fromName = (networkName: StacksNetworkName): StacksNetwork => { | ||
switch (networkName) { | ||
case 'mainnet': | ||
return new StacksMainnet(); | ||
case 'testnet': | ||
return new StacksTestnet(); | ||
case 'devnet': | ||
return new StacksDevnet(); | ||
case 'mocknet': | ||
return new StacksMocknet(); | ||
default: | ||
throw new Error( | ||
`Invalid network name provided. Must be one of the following: ${StacksNetworks.join( | ||
', ' | ||
)}` | ||
); | ||
} | ||
}; | ||
/** @ignore internal */ | ||
static fromNameOrNetwork = (network: StacksNetworkName | StacksNetwork) => { | ||
if (typeof network !== 'string' && 'version' in network) { | ||
return network; | ||
} | ||
return StacksNetwork.fromName(network); | ||
}; | ||
/** Returns `true` if the network is configured to 'mainnet', based on the TransactionVersion */ | ||
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`; | ||
getAccountExtendedBalancesApiUrl = (address: string) => | ||
`${this.coreApiUrl}/extended/v1/address/${address}/balances`; | ||
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`; | ||
getDataVarUrl = (contractAddress: string, contractName: string, dataVarName: string) => | ||
`${this.coreApiUrl}/v2/data_var/${contractAddress}/${contractName}/${dataVarName}?proof=0`; | ||
getMapEntryUrl = (contractAddress: string, contractName: string, mapName: string) => | ||
`${this.coreApiUrl}/v2/map_entry/${contractAddress}/${contractName}/${mapName}?proof=0`; | ||
getNameInfo(fullyQualifiedName: string) { | ||
/* | ||
TODO: Update to v2 API URL for name lookups | ||
*/ | ||
const nameLookupURL = `${this.bnsLookupUrl}/v1/names/${fullyQualifiedName}`; | ||
return this.fetchFn(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 --- | ||
// stacks node 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; | ||
} | ||
}); | ||
} | ||
} | ||
/** | ||
* A {@link StacksNetwork} with the parameters for the Stacks mainnet. | ||
* Pass a `url` option to override the default Hiro hosted Stacks node API. | ||
* Pass a `fetchFn` option to customize the default networking functions. | ||
* @example | ||
* ``` | ||
* const network = new StacksMainnet(); | ||
* const network = new StacksMainnet({ url: "https://api.mainnet.hiro.so" }); | ||
* const network = new StacksMainnet({ fetch: createFetchFn() }); | ||
* ``` | ||
* @related {@link createFetchFn}, {@link createApiKeyMiddleware} | ||
*/ | ||
export class StacksMainnet extends StacksNetwork { | ||
version = TransactionVersion.Mainnet; | ||
chainId = ChainID.Mainnet; | ||
constructor(opts?: Partial<NetworkConfig>) { | ||
super({ | ||
url: opts?.url ?? HIRO_MAINNET_DEFAULT, | ||
fetchFn: opts?.fetchFn, | ||
}); | ||
} | ||
export function networkFrom(network: StacksNetworkName | StacksNetwork) { | ||
if (typeof network === 'string') return networkFromName(network); | ||
return network; | ||
} | ||
/** | ||
* A {@link StacksNetwork} with the parameters for the Stacks testnet. | ||
* Pass a `url` option to override the default Hiro hosted Stacks node API. | ||
* Pass a `fetchFn` option to customize the default networking functions. | ||
* @example | ||
* ``` | ||
* const network = new StacksTestnet(); | ||
* const network = new StacksTestnet({ url: "https://api.testnet.hiro.so" }); | ||
* const network = new StacksTestnet({ fetch: createFetchFn() }); | ||
* ``` | ||
* @related {@link createFetchFn}, {@link createApiKeyMiddleware} | ||
*/ | ||
export class StacksTestnet extends StacksNetwork { | ||
version = TransactionVersion.Testnet; | ||
chainId = ChainID.Testnet; | ||
export function deriveDefaultUrl(network: StacksNetwork | StacksNetworkName | undefined) { | ||
if (!network) return HIRO_MAINNET_URL; // default to mainnet if no network is given | ||
constructor(opts?: Partial<NetworkConfig>) { | ||
super({ | ||
url: opts?.url ?? HIRO_TESTNET_DEFAULT, | ||
fetchFn: opts?.fetchFn, | ||
}); | ||
} | ||
} | ||
network = networkFrom(network); | ||
/** | ||
* A {@link StacksNetwork} using the testnet parameters, but `localhost:3999` as the API URL. | ||
*/ | ||
export class StacksMocknet extends StacksNetwork { | ||
version = TransactionVersion.Testnet; | ||
chainId = ChainID.Testnet; | ||
constructor(opts?: Partial<NetworkConfig>) { | ||
super({ | ||
url: opts?.url ?? HIRO_MOCKNET_DEFAULT, | ||
fetchFn: opts?.fetchFn, | ||
}); | ||
} | ||
return !network || network.transactionVersion === TransactionVersion.Mainnet | ||
? HIRO_MAINNET_URL // default to mainnet if txVersion is mainnet | ||
: network.magicBytes === 'id' | ||
? DEVNET_URL // default to devnet if magicBytes are devnet | ||
: HIRO_TESTNET_URL; | ||
} | ||
/** Alias for {@link StacksMocknet} */ | ||
export const StacksDevnet = StacksMocknet; |
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
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
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
Manifest confusion
Supply chain riskThis package has inconsistent metadata. This could be malicious or caused by an error when publishing the package.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Network access
Supply chain riskThis module accesses the network.
Found 1 instance in 1 package
2
35150
337