From affa2c911537039da88c4ec6879509e862b3f137 Mon Sep 17 00:00:00 2001 From: janniks Date: Mon, 14 Oct 2024 18:09:27 +0200 Subject: [PATCH] test: Update to succeed tests --- package-lock.json | 2 - packages/cli/package.json | 1 - packages/cli/src/cli.ts | 240 ++++++++++--------- packages/cli/tsconfig.build.json | 3 - packages/internal/package.json | 1 - packages/internal/src/apiMockingHelpers.ts | 19 +- packages/internal/tsconfig.build.json | 3 - packages/stacking/src/index.ts | 23 +- packages/stacking/tests/stacking-2.4.test.ts | 138 ++++++++--- packages/stacking/tests/stacking.test.ts | 147 +++++++++--- packages/stacking/tsconfig.build.json | 3 - 11 files changed, 366 insertions(+), 214 deletions(-) diff --git a/package-lock.json b/package-lock.json index 97f264e88..d73de9ebb 100644 --- a/package-lock.json +++ b/package-lock.json @@ -22288,7 +22288,6 @@ "dependencies": { "@scure/bip32": "1.1.3", "@scure/bip39": "1.1.0", - "@stacks/api": "file:../api", "@stacks/auth": "^6.16.1", "@stacks/blockchain-api-client": "4.0.1", "@stacks/bns": "^6.16.1", @@ -22435,7 +22434,6 @@ "packages/internal": { "name": "@stacks/internal", "devDependencies": { - "@stacks/api": "^6.9.0", "@stacks/blockchain-api-client": "^7.12.0", "@stacks/network": "^6.16.0", "@stacks/stacking": "^6.9.0", diff --git a/packages/cli/package.json b/packages/cli/package.json index d9b14e812..bb07e19f1 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -22,7 +22,6 @@ "dependencies": { "@scure/bip32": "1.1.3", "@scure/bip39": "1.1.0", - "@stacks/api": "file:../api", "@stacks/auth": "^6.16.1", "@stacks/blockchain-api-client": "4.0.1", "@stacks/bns": "^6.16.1", diff --git a/packages/cli/src/cli.ts b/packages/cli/src/cli.ts index bde5d01b2..73a842900 100644 --- a/packages/cli/src/cli.ts +++ b/packages/cli/src/cli.ts @@ -1,6 +1,5 @@ import * as scureBip39 from '@scure/bip39'; import { wordlist } from '@scure/bip39/wordlists/english'; -import { StacksNodeApi } from '@stacks/api'; import { buildPreorderNameTx, buildRegisterNameTx } from '@stacks/bns'; import { bytesToHex, HIRO_MAINNET_URL, HIRO_TESTNET_URL } from '@stacks/common'; import { @@ -91,7 +90,12 @@ import { CLI_NETWORK_OPTS, CLINetworkAdapter, getNetwork, NameInfoType } from '. import { gaiaAuth, gaiaConnect, gaiaUploadProfileAll, getGaiaAddressFromProfile } from './data'; -import { defaultUrlFromNetwork, STACKS_MAINNET, STACKS_TESTNET } from '@stacks/network'; +import { + defaultClientOptsFromNetwork, + defaultUrlFromNetwork, + STACKS_MAINNET, + STACKS_TESTNET, +} from '@stacks/network'; import { generateNewAccount, generateWallet, @@ -136,7 +140,7 @@ let BLOCKSTACK_TEST = !!process.env.BLOCKSTACK_TEST; */ // TODO: fix, network is never used // @ts-ignore -function profileSign(network: CLINetworkAdapter, args: string[]): Promise { +function profileSign(_network: CLINetworkAdapter, args: string[]): Promise { const profilePath = args[0]; const profileData = JSON.parse(fs.readFileSync(profilePath).toString()); return Promise.resolve().then(() => makeProfileJWT(profileData, args[1])); @@ -147,13 +151,13 @@ function profileSign(network: CLINetworkAdapter, args: string[]): Promise { +function profileVerify(_network: CLINetworkAdapter, args: string[]): Promise { const profilePath = args[0]; let publicKeyOrAddress = args[1]; // need to coerce mainnet if (publicKeyOrAddress.match(ID_ADDRESS_PATTERN)) { - publicKeyOrAddress = network.coerceMainnetAddress(publicKeyOrAddress.slice(3)); + publicKeyOrAddress = _network.coerceMainnetAddress(publicKeyOrAddress.slice(3)); } const profileString = fs.readFileSync(profilePath).toString(); @@ -190,7 +194,7 @@ function profileVerify(network: CLINetworkAdapter, args: string[]): Promise { +function profileStore(_network: CLINetworkAdapter, args: string[]): Promise { const nameOrAddress = args[0]; const signedProfilePath = args[1]; const privateKey = decodePrivateKey(args[2]); @@ -198,8 +202,8 @@ function profileStore(network: CLINetworkAdapter, args: string[]): Promise; let name = ''; @@ -213,11 +217,11 @@ function profileStore(network: CLINetworkAdapter, args: string[]): Promise { if (gaiaUrls.hasOwnProperty('error')) { @@ -253,7 +257,7 @@ function profileStore(network: CLINetworkAdapter, args: string[]): Promise { +async function getAppKeys(_network: CLINetworkAdapter, args: string[]): Promise { const mnemonic = await getBackupPhrase(args[0]); const index = parseInt(args[1]); if (index <= 0) throw new Error('index must be greater than 0'); @@ -266,7 +270,7 @@ async function getAppKeys(network: CLINetworkAdapter, args: string[]): Promise { +async function getOwnerKeys(_network: CLINetworkAdapter, args: string[]): Promise { const mnemonic = await getBackupPhrase(args[0]); let maxIndex = 1; if (args.length > 1 && !!args[1]) { @@ -287,7 +291,7 @@ async function getOwnerKeys(network: CLINetworkAdapter, args: string[]): Promise const keyInfo: OwnerKeyInfoType[] = []; for (let i = 0; i < maxIndex; i++) { - keyInfo.push(await getOwnerKeyInfo(network, mnemonic, i)); + keyInfo.push(await getOwnerKeyInfo(_network, mnemonic, i)); } return JSONStringify(keyInfo); @@ -298,10 +302,10 @@ async function getOwnerKeys(network: CLINetworkAdapter, args: string[]): Promise * args: * @mnemonic (string) the 12-word phrase */ -async function getPaymentKey(network: CLINetworkAdapter, args: string[]): Promise { +async function getPaymentKey(_network: CLINetworkAdapter, args: string[]): Promise { const mnemonic = await getBackupPhrase(args[0]); // keep the return value consistent with getOwnerKeys - const keyObj = await getPaymentKeyInfo(network, mnemonic); + const keyObj = await getPaymentKeyInfo(_network, mnemonic); const keyInfo: PaymentKeyInfoType[] = []; keyInfo.push(keyObj); return JSONStringify(keyInfo); @@ -312,11 +316,11 @@ async function getPaymentKey(network: CLINetworkAdapter, args: string[]): Promis * args: * @mnemonic (string) the 24-word phrase */ -async function getStacksWalletKey(network: CLINetworkAdapter, args: string[]): Promise { +async function getStacksWalletKey(_network: CLINetworkAdapter, args: string[]): Promise { const mnemonic = await getBackupPhrase(args[0]); const derivationPath: string | undefined = args[1] || undefined; // keep the return value consistent with getOwnerKeys - const keyObj = await getStacksWalletKeyInfo(network, mnemonic, derivationPath); + const keyObj = await getStacksWalletKeyInfo(_network, mnemonic, derivationPath); const keyInfo: StacksKeyInfoType[] = []; keyInfo.push(keyObj); return JSONStringify(keyInfo); @@ -329,14 +333,14 @@ async function getStacksWalletKey(network: CLINetworkAdapter, args: string[]): P * @mnemonic (string) the seed phrase to retrieve the privateKey & address * @registrarUrl (string) URL of the registrar to use (defaults to 'https://registrar.stacks.co') */ -async function migrateSubdomains(network: CLINetworkAdapter, args: string[]): Promise { +async function migrateSubdomains(_network: CLINetworkAdapter, args: string[]): Promise { const mnemonic: string = await getBackupPhrase(args[0]); // args[0] is the cli argument for mnemonic const baseWallet = await generateWallet({ secretKey: mnemonic, password: '' }); - const _network = network.isMainnet() ? STACKS_MAINNET : STACKS_TESTNET; + const network = _network.isMainnet() ? STACKS_MAINNET : STACKS_TESTNET; const wallet = await restoreWalletAccounts({ wallet: baseWallet, gaiaHubUrl: 'https://hub.blockstack.org', - network: _network, + network, }); console.log( `Accounts found: ${wallet.accounts.length}\n(Accounts will be checked for both compressed and uncompressed public keys)` @@ -354,12 +358,12 @@ async function migrateSubdomains(network: CLINetworkAdapter, args: string[]): Pr for (const account of accounts) { console.log('\nAccount:', account); - const dataKeyAddress = getAddressFromPrivateKey(account.dataPrivateKey, _network); // source - const walletKeyAddress = getAddressFromPrivateKey(account.stxPrivateKey, _network); // target + const dataKeyAddress = getAddressFromPrivateKey(account.dataPrivateKey, network); // source + const walletKeyAddress = getAddressFromPrivateKey(account.stxPrivateKey, network); // target console.log(`Finding subdomains for data-key address '${dataKeyAddress}'`); const namesResponse = await fetch( - `${defaultUrlFromNetwork(_network)}/v1/addresses/stacks/${dataKeyAddress}` + `${defaultUrlFromNetwork(network)}/v1/addresses/stacks/${dataKeyAddress}` ); const namesJson = await namesResponse.json(); @@ -377,7 +381,7 @@ async function migrateSubdomains(network: CLINetworkAdapter, args: string[]): Pr // Alerts the user to any subdomains that can't be migrated to these wallet-key-derived addresses // Given collision with existing usernames owned by them const namesResponse = await fetch( - `${defaultUrlFromNetwork(_network)}/v1/addresses/stacks/${walletKeyAddress}` + `${defaultUrlFromNetwork(network)}/v1/addresses/stacks/${walletKeyAddress}` ); const existingNames = await namesResponse.json(); if (existingNames.names?.includes(subdomain)) { @@ -386,7 +390,7 @@ async function migrateSubdomains(network: CLINetworkAdapter, args: string[]): Pr } // Validate user owns the subdomain - const nameInfo = await fetch(`${defaultUrlFromNetwork(_network)}/v1/names/${subdomain}`); + const nameInfo = await fetch(`${defaultUrlFromNetwork(network)}/v1/names/${subdomain}`); const nameInfoJson = await nameInfo.json(); console.log('Subdomain Info: ', nameInfoJson); if (nameInfoJson.address !== dataKeyAddress) { @@ -411,7 +415,7 @@ async function migrateSubdomains(network: CLINetworkAdapter, args: string[]): Pr subdomainName, owner: walletKeyAddress, // new owner address / wallet-key address (compressed) zonefile: nameInfoJson.zonefile, - sequenceNumber: 1, // should be 'old sequence number + 1', but cannot find old sequence number so assuming 1. Api should calculate it again. + sequenceNumber: 1, // should be 'old sequence number + 1', but cannot find old sequence number so assuming 1. client should calculate it again. }; const subdomainPieces = subdomainOpToZFPieces(subDomainOp); @@ -484,13 +488,13 @@ async function migrateSubdomains(network: CLINetworkAdapter, args: string[]): Pr * args: * @mnemonic (string) OPTIONAL; the 12-word phrase */ -async function makeKeychain(network: CLINetworkAdapter, args: string[]): Promise { +async function makeKeychain(_network: CLINetworkAdapter, args: string[]): Promise { const mnemonic: string = args[0] ? await getBackupPhrase(args[0]) : scureBip39.generateMnemonic(wordlist, STX_WALLET_COMPATIBLE_SEED_STRENGTH); const derivationPath: string | undefined = args[1] || undefined; - const stacksKeyInfo = await getStacksWalletKeyInfo(network, mnemonic, derivationPath); + const stacksKeyInfo = await getStacksWalletKeyInfo(_network, mnemonic, derivationPath); return JSONStringify({ mnemonic, @@ -504,16 +508,16 @@ async function makeKeychain(network: CLINetworkAdapter, args: string[]): Promise * args: * @address (string) the address */ -function balance(network: CLINetworkAdapter, args: string[]): Promise { +function balance(_network: CLINetworkAdapter, args: string[]): Promise { let address = args[0]; if (BLOCKSTACK_TEST) { // force testnet address if we're in testnet mode - address = network.coerceAddress(address); + address = _network.coerceAddress(address); } // temporary hack to use network config from stacks-transactions lib - const url = network.isMainnet() ? HIRO_MAINNET_URL : HIRO_TESTNET_URL; + const url = _network.isMainnet() ? HIRO_MAINNET_URL : HIRO_TESTNET_URL; return fetch(`${url}${ACCOUNT_PATH}/${address}?proof=0`) .then(response => { @@ -543,14 +547,14 @@ function balance(network: CLINetworkAdapter, args: string[]): Promise { * @address (string) the account address * @page (int) the page of the history to fetch (optional) */ -function getAccountHistory(network: CLINetworkAdapter, args: string[]): Promise { +function getAccountHistory(_network: CLINetworkAdapter, args: string[]): Promise { const address = c32check.c32ToB58(args[0]); if (args.length >= 2 && !!args[1]) { const page = parseInt(args[1]); return Promise.resolve() .then(() => { - return network.getAccountHistoryPage(address, page); + return _network.getAccountHistoryPage(address, page); }) .then(accountStates => JSONStringify( @@ -569,7 +573,7 @@ function getAccountHistory(network: CLINetworkAdapter, args: string[]): Promise< let history: any[] = []; function getAllAccountHistoryPages(page: number): Promise { - return network.getAccountHistoryPage(address, page).then((results: any[]) => { + return _network.getAccountHistoryPage(address, page).then((results: any[]) => { if (results.length == 0) { return history; } else { @@ -680,7 +684,7 @@ function getAccountHistory(network: CLINetworkAdapter, args: string[]): Promise< * @privateKey (string) the hex-encoded private key to use to send the tokens * @memo (string) OPTIONAL: a 34-byte memo to include */ -async function sendTokens(network: CLINetworkAdapter, args: string[]): Promise { +async function sendTokens(_network: CLINetworkAdapter, args: string[]): Promise { const recipientAddress = args[0]; const tokenAmount = BigInt(args[1]); const fee = BigInt(args[2]); @@ -693,8 +697,8 @@ async function sendTokens(network: CLINetworkAdapter, args: string[]): Promise { + return fetchFeeEstimateTransfer({ transaction: tx, client }).then(cost => { return cost.toString(10); }); } @@ -718,14 +722,14 @@ async function sendTokens(network: CLINetworkAdapter, args: string[]): Promise { if (response.hasOwnProperty('error')) { return response; } return { txid: `0x${tx.txid()}`, - transaction: generateExplorerTxPageUrl(tx.txid(), api.network), + transaction: generateExplorerTxPageUrl(tx.txid(), network), }; }) .catch(error => { @@ -742,7 +746,7 @@ async function sendTokens(network: CLINetworkAdapter, args: string[]): Promise { +async function contractDeploy(_network: CLINetworkAdapter, args: string[]): Promise { const sourceFile = args[0]; const contractName = args[1]; const fee = BigInt(args[2]); @@ -751,8 +755,7 @@ async function contractDeploy(network: CLINetworkAdapter, args: string[]): Promi const source = fs.readFileSync(sourceFile).toString(); - // temporary hack to use network config from stacks-transactions lib - const api = new StacksNodeApi({ network: network.isMainnet() ? STACKS_MAINNET : STACKS_TESTNET }); + const network = _network.isMainnet() ? STACKS_MAINNET : STACKS_TESTNET; const options: SignedContractDeployOptions = { contractName, @@ -760,7 +763,7 @@ async function contractDeploy(network: CLINetworkAdapter, args: string[]): Promi senderKey: privateKey, fee, nonce, - network: api.network, + network, postConditionMode: PostConditionMode.Allow, }; @@ -784,7 +787,7 @@ async function contractDeploy(network: CLINetworkAdapter, args: string[]): Promi } return { txid: `0x${tx.txid()}`, - transaction: generateExplorerTxPageUrl(tx.txid(), api.network), + transaction: generateExplorerTxPageUrl(tx.txid(), network), }; }) .catch(error => { @@ -802,7 +805,7 @@ async function contractDeploy(network: CLINetworkAdapter, args: string[]): Promi * @nonce (int) integer nonce needs to be incremented after each transaction from an account * @privateKey (string) the hex-encoded private key to use to send the tokens */ -async function contractFunctionCall(network: CLINetworkAdapter, args: string[]): Promise { +async function contractFunctionCall(_network: CLINetworkAdapter, args: string[]): Promise { const contractAddress = args[0]; const contractName = args[1]; const functionName = args[2]; @@ -811,13 +814,14 @@ async function contractFunctionCall(network: CLINetworkAdapter, args: string[]): const privateKey = args[5]; // temporary hack to use network config from stacks-transactions lib - const api = new StacksNodeApi({ network: network.isMainnet() ? STACKS_MAINNET : STACKS_TESTNET }); + const network = _network.isMainnet() ? STACKS_MAINNET : STACKS_TESTNET; + const client = defaultClientOptsFromNetwork(network); let abi: ClarityAbi; let abiArgs: ClarityFunctionArg[]; let functionArgs: ClarityValue[] = []; - return fetchAbi({ contractAddress, contractName, api }) + return fetchAbi({ contractAddress, contractName, client }) .then(responseAbi => { abi = responseAbi; const filtered = abi.functions.filter(fn => fn.name === functionName); @@ -840,9 +844,9 @@ async function contractFunctionCall(network: CLINetworkAdapter, args: string[]): senderKey: privateKey, fee, nonce, - network: api.network, + network, postConditionMode: PostConditionMode.Allow, - api, + client, }; return makeContractCall(options); @@ -863,14 +867,14 @@ async function contractFunctionCall(network: CLINetworkAdapter, args: string[]): return Promise.resolve(tx.serialize()); } - return broadcastTransaction({ transaction: tx, api }) + return broadcastTransaction({ transaction: tx, client }) .then(response => { if (response.hasOwnProperty('error')) { return response; } return { txid: `0x${tx.txid()}`, - transaction: generateExplorerTxPageUrl(tx.txid(), api.network), + transaction: generateExplorerTxPageUrl(tx.txid(), network), }; }) .catch(error => { @@ -888,7 +892,7 @@ async function contractFunctionCall(network: CLINetworkAdapter, args: string[]): * @senderAddress (string) the sender address */ async function readOnlyContractFunctionCall( - network: CLINetworkAdapter, + _network: CLINetworkAdapter, args: string[] ): Promise { const contractAddress = args[0]; @@ -896,14 +900,14 @@ async function readOnlyContractFunctionCall( const functionName = args[2]; const senderAddress = args[3]; - // temporary hack to use network config from stacks-transactions lib - const api = new StacksNodeApi({ network: network.isMainnet() ? STACKS_MAINNET : STACKS_TESTNET }); + const network = _network.isMainnet() ? STACKS_MAINNET : STACKS_TESTNET; + const client = defaultClientOptsFromNetwork(network); let abi: ClarityAbi; let abiArgs: ClarityFunctionArg[]; let functionArgs: ClarityValue[] = []; - return fetchAbi({ contractAddress, contractName, api }) + return fetchAbi({ contractAddress, contractName, client }) .then(responseAbi => { abi = responseAbi; const filtered = abi.functions.filter(fn => fn.name === functionName); @@ -924,7 +928,7 @@ async function readOnlyContractFunctionCall( functionName, functionArgs, senderAddress, - network: api.network, + network, }; return fetchCallReadOnlyFunction(options); @@ -1000,10 +1004,10 @@ function decodeCV(_network: CLINetworkAdapter, args: string[]): Promise * args: * @private_key (string) the hex-encoded private key or key bundle */ -function getKeyAddress(network: CLINetworkAdapter, args: string[]): Promise { +function getKeyAddress(_network: CLINetworkAdapter, args: string[]): Promise { const privateKey = decodePrivateKey(args[0]); return Promise.resolve().then(() => { - const addr = getPrivateKeyAddress(network, privateKey); + const addr = getPrivateKeyAddress(_network, privateKey); return JSONStringify({ BTC: addr, STACKS: c32check.b58ToC32(addr), @@ -1022,7 +1026,7 @@ function getKeyAddress(network: CLINetworkAdapter, args: string[]): Promise { +function gaiaGetFile(_network: CLINetworkAdapter, args: string[]): Promise { const username = args[0]; const origin = args[1]; const path = args[2]; @@ -1045,7 +1049,7 @@ function gaiaGetFile(network: CLINetworkAdapter, args: string[]): Promise blockstack.getFile(path, { decrypt: decrypt, @@ -1073,7 +1077,7 @@ function gaiaGetFile(network: CLINetworkAdapter, args: string[]): Promise { +function gaiaPutFile(_network: CLINetworkAdapter, args: string[]): Promise { const hubUrl = args[0]; const appPrivateKey = args[1]; const dataPath = args[2]; @@ -1094,7 +1098,7 @@ function gaiaPutFile(network: CLINetworkAdapter, args: string[]): Promise { return blockstack.putFile(gaiaPath, data, { encrypt: encrypt, sign: sign }); }) @@ -1111,7 +1115,7 @@ function gaiaPutFile(network: CLINetworkAdapter, args: string[]): Promise { +function gaiaDeleteFile(_network: CLINetworkAdapter, args: string[]): Promise { const hubUrl = args[0]; const appPrivateKey = args[1]; const gaiaPath = path.normalize(args[2].replace(/^\/+/, '')); @@ -1125,7 +1129,7 @@ function gaiaDeleteFile(network: CLINetworkAdapter, args: string[]): Promise { return blockstack.deleteFile(gaiaPath, { wasSigned: wasSigned }); }) @@ -1140,7 +1144,7 @@ function gaiaDeleteFile(network: CLINetworkAdapter, args: string[]): Promise { +function gaiaListFiles(_network: CLINetworkAdapter, args: string[]): Promise { const hubUrl = args[0]; const appPrivateKey = args[1]; @@ -1148,7 +1152,7 @@ function gaiaListFiles(network: CLINetworkAdapter, args: string[]): Promise { return blockstack.listFiles((name: string) => { // print out incrementally @@ -1195,7 +1199,7 @@ function sleep(ms: number) { * @mnemonic (string) the 12-word phrase or ciphertext * @dumpDir (string) the directory to hold the dumped files */ -function gaiaDumpBucket(network: CLINetworkAdapter, args: string[]): Promise { +function gaiaDumpBucket(_network: CLINetworkAdapter, args: string[]): Promise { const nameOrIDAddress = args[0]; const appOrigin = args[1]; const hubUrl = args[2]; @@ -1258,14 +1262,14 @@ function gaiaDumpBucket(network: CLINetworkAdapter, args: string[]): Promise { appPrivateKey = keyInfo.appPrivateKey; ownerPrivateKey = keyInfo.ownerPrivateKey; - return gaiaAuth(network, appPrivateKey, hubUrl, ownerPrivateKey); + return gaiaAuth(_network, appPrivateKey, hubUrl, ownerPrivateKey); }) .then((_userData: UserData) => { - return gaiaConnect(network, hubUrl, appPrivateKey); + return gaiaConnect(_network, hubUrl, appPrivateKey); }) .then((hubConfig: GaiaHubConfig) => { gaiaHubConfig = hubConfig; @@ -1311,7 +1315,7 @@ function gaiaDumpBucket(network: CLINetworkAdapter, args: string[]): Promise { +function gaiaRestoreBucket(_network: CLINetworkAdapter, args: string[]): Promise { const nameOrIDAddress = args[0]; const appOrigin = args[1]; const hubUrl = args[2]; @@ -1337,11 +1341,11 @@ function gaiaRestoreBucket(network: CLINetworkAdapter, args: string[]): Promise< // TODO better way of doing this blockstack.config.network.layer1 = bitcoin.networks.bitcoin; - return getIDAppKeys(network, nameOrIDAddress, appOrigin, mnemonicOrCiphertext) + return getIDAppKeys(_network, nameOrIDAddress, appOrigin, mnemonicOrCiphertext) .then((keyInfo: IDAppKeys) => { appPrivateKey = keyInfo.appPrivateKey; ownerPrivateKey = keyInfo.ownerPrivateKey; - return gaiaAuth(network, appPrivateKey, hubUrl, ownerPrivateKey); + return gaiaAuth(_network, appPrivateKey, hubUrl, ownerPrivateKey); }) .then(async (_userData: UserData) => { const batchSize = 99; @@ -1378,8 +1382,8 @@ function gaiaRestoreBucket(network: CLINetworkAdapter, args: string[]): Promise< * @hubUrl (string) the URL to the write endpoint of the app's gaia hub * @mnemonic (string) the 12-word backup phrase, or the ciphertext of it */ -async function gaiaSetHub(network: CLINetworkAdapter, args: string[]): Promise { - network.setCoerceMainnetAddress(true); +async function gaiaSetHub(_network: CLINetworkAdapter, args: string[]): Promise { + _network.setCoerceMainnetAddress(true); const blockstackID = args[0]; const ownerHubUrl = args[1]; @@ -1387,7 +1391,7 @@ async function gaiaSetHub(network: CLINetworkAdapter, args: string[]): Promise { if (!nameInfo) { throw new Error('Name not found'); @@ -1419,26 +1423,26 @@ async function gaiaSetHub(network: CLINetworkAdapter, args: string[]): Promise { +function addressConvert(_network: CLINetworkAdapter, args: string[]): Promise { const addr = args[0]; let b58addr: string; let testnetb58addr: string; @@ -1516,12 +1520,12 @@ function addressConvert(network: CLINetworkAdapter, args: string[]): Promise { - const mainnetb58addr = network.coerceMainnetAddress(b58addr); + const mainnetb58addr = _network.coerceMainnetAddress(b58addr); const result: any = { mainnet: { STACKS: c32check.b58ToC32(mainnetb58addr), @@ -1549,7 +1553,7 @@ function addressConvert(network: CLINetworkAdapter, args: string[]): Promise { +function encryptMnemonic(_network: CLINetworkAdapter, args: string[]): Promise { const mnemonic = args[0]; if (mnemonic.split(/ +/g).length !== 12) { throw new Error('Invalid backup phrase: must be 12 words'); @@ -1596,7 +1600,7 @@ function encryptMnemonic(network: CLINetworkAdapter, args: string[]): Promise { +function decryptMnemonic(_network: CLINetworkAdapter, args: string[]): Promise { const ciphertext = args[0]; const passwordPromise: Promise = new Promise((resolve, reject) => { @@ -1630,15 +1634,15 @@ async function stackingStatus(_network: CLINetworkAdapter, args: string[]): Prom const address = args[0]; const network = _network.isMainnet() ? STACKS_MAINNET : STACKS_TESTNET; - const api = new StacksNodeApi({ network }); - const stacker = new StackingClient({ address, network, api }); + const client = defaultClientOptsFromNetwork(network); + const stacker = new StackingClient({ address, network, client }); return stacker .getStatus() .then((status: StackerInfo) => { if (status.stacked) { return { - // amount_microstx: status.details.amount_microstx, // todo: add again via other api call? + // amount_microstx: status.details.amount_microstx, // todo: add again via other client call? first_reward_cycle: status.details.first_reward_cycle, lock_period: status.details.lock_period, unlock_height: status.details.unlock_height, @@ -1663,11 +1667,11 @@ async function canStack(_network: CLINetworkAdapter, args: string[]): Promise { @@ -1791,34 +1795,35 @@ async function stack(_network: CLINetworkAdapter, args: string[]): Promise { +async function register(_network: CLINetworkAdapter, args: string[]): Promise { const fullyQualifiedName = args[0]; const privateKey = args[1]; const salt = args[2]; const zonefile = args[3]; const publicKey = privateKeyToPublic(privateKey); - const api = new StacksNodeApi({ network: network.isMainnet() ? STACKS_MAINNET : STACKS_TESTNET }); + const network = _network.isMainnet() ? STACKS_MAINNET : STACKS_TESTNET; + const client = defaultClientOptsFromNetwork(network); const unsignedTransaction = await buildRegisterNameTx({ fullyQualifiedName, publicKey, salt, zonefile, - network: api.network, + network, }); const signer = new TransactionSigner(unsignedTransaction); signer.signOrigin(privateKey); - return broadcastTransaction({ transaction: signer.transaction, api }) + return broadcastTransaction({ transaction: signer.transaction, client }) .then((response: TxBroadcastResult) => { if (response.hasOwnProperty('error')) { return response; } return { txid: `0x${response.txid}`, - transaction: generateExplorerTxPageUrl(response.txid, api.network), + transaction: generateExplorerTxPageUrl(response.txid, network), }; }) .catch(error => { @@ -1826,34 +1831,35 @@ async function register(network: CLINetworkAdapter, args: string[]): Promise { +async function preorder(_network: CLINetworkAdapter, args: string[]): Promise { const fullyQualifiedName = args[0]; const privateKey = args[1]; const salt = args[2]; const stxToBurn = args[3]; const publicKey = privateKeyToPublic(privateKey); - const api = new StacksNodeApi({ network: network.isMainnet() ? STACKS_MAINNET : STACKS_TESTNET }); + const network = _network.isMainnet() ? STACKS_MAINNET : STACKS_TESTNET; + const client = defaultClientOptsFromNetwork(network); const unsignedTransaction = await buildPreorderNameTx({ fullyQualifiedName, publicKey, salt, stxToBurn, - network: api.network, + network, }); const signer = new TransactionSigner(unsignedTransaction); signer.signOrigin(privateKey); - return broadcastTransaction({ transaction: signer.transaction, api }) + return broadcastTransaction({ transaction: signer.transaction, client }) .then((response: TxBroadcastResult) => { if (response.hasOwnProperty('error')) { return response; } return { txid: `0x${response.txid}`, - transaction: generateExplorerTxPageUrl(response.txid, api.network), + transaction: generateExplorerTxPageUrl(response.txid, network), }; }) .catch(error => { diff --git a/packages/cli/tsconfig.build.json b/packages/cli/tsconfig.build.json index 5b9dd5f40..5845d0f58 100644 --- a/packages/cli/tsconfig.build.json +++ b/packages/cli/tsconfig.build.json @@ -8,9 +8,6 @@ "composite": true }, "references": [ - { - "path": "../api/tsconfig.build.json" - }, { "path": "../auth/tsconfig.build.json" }, diff --git a/packages/internal/package.json b/packages/internal/package.json index 2642bc5df..d706d6261 100644 --- a/packages/internal/package.json +++ b/packages/internal/package.json @@ -7,7 +7,6 @@ "typecheck:watch": "npm run typecheck -- --watch" }, "devDependencies": { - "@stacks/api": "^6.9.0", "@stacks/stacking": "^6.9.0", "@stacks/blockchain-api-client": "^7.12.0", "@stacks/network": "^6.16.0", diff --git a/packages/internal/src/apiMockingHelpers.ts b/packages/internal/src/apiMockingHelpers.ts index a9d761d03..df1254e93 100644 --- a/packages/internal/src/apiMockingHelpers.ts +++ b/packages/internal/src/apiMockingHelpers.ts @@ -2,7 +2,6 @@ import { Configuration, TransactionsApi } from '@stacks/blockchain-api-client'; import { STACKS_TESTNET } from '@stacks/network'; import { MockResponseInitFunction } from 'jest-fetch-mock'; import { StackingClient } from '@stacks/stacking'; -import { StacksNodeApi } from '@stacks/api'; // NOTES // Capture traffic via the fetchWrapper @@ -93,8 +92,13 @@ export async function waitForTx(txId: string, apiUrl = 'http://localhost:3999') export async function waitForBlock(burnBlockId: number, client?: StackingClient) { if (isMocking()) return; - const api = { url: 'http://localhost:3999' }; - client = client ?? new StackingClient({ address: '', network: STACKS_TESTNET, api }); + client = + client ?? + new StackingClient({ + address: '', + network: STACKS_TESTNET, + client: { baseUrl: 'http://localhost:3999' }, + }); let current: number; for (let i = 1; i <= MAX_ITERATIONS; i++) { @@ -117,8 +121,13 @@ export async function waitForBlock(burnBlockId: number, client?: StackingClient) export async function waitForCycle(cycleId: number, client?: StackingClient) { if (isMocking()) return; - const api = new StacksNodeApi({ url: 'http://localhost:3999' }); - client = client ?? new StackingClient({ address: '', network: STACKS_TESTNET, api }); + client = + client ?? + new StackingClient({ + address: '', + network: STACKS_TESTNET, + client: { baseUrl: 'http://localhost:3999' }, + }); let current: number; for (let i = 1; i <= MAX_ITERATIONS; i++) { diff --git a/packages/internal/tsconfig.build.json b/packages/internal/tsconfig.build.json index e65f27fb7..4214e866e 100644 --- a/packages/internal/tsconfig.build.json +++ b/packages/internal/tsconfig.build.json @@ -8,9 +8,6 @@ "composite": true }, "references": [ - { - "path": "../api/tsconfig.build.json" - }, { "path": "../stacking/tsconfig.build.json" } diff --git a/packages/stacking/src/index.ts b/packages/stacking/src/index.ts index 2887117bd..5fb88e642 100644 --- a/packages/stacking/src/index.ts +++ b/packages/stacking/src/index.ts @@ -1,12 +1,11 @@ +import { ClientOpts, IntegerType, PrivateKey, hexToBytes, intToBigInt } from '@stacks/common'; import { - ClientOpts, - IntegerType, - PrivateKey, - defaultClientOpts, - hexToBytes, - intToBigInt, -} from '@stacks/common'; -import { ChainId, StacksNetwork, StacksNetworkName, networkFrom } from '@stacks/network'; + ChainId, + StacksNetwork, + StacksNetworkName, + defaultClientOptsFromNetwork, + networkFrom, +} from '@stacks/network'; import { BurnchainRewardListResponse, BurnchainRewardSlotHolderListResponse, @@ -342,7 +341,7 @@ export class StackingClient { }) { this.address = opts.address; this.network = networkFrom(opts.network); - this.client = defaultClientOpts(opts.client); + this.client = defaultClientOptsFromNetwork(this.network, opts.client); } get baseUrl() { @@ -353,17 +352,17 @@ export class StackingClient { return this.client.fetch; } - /** @deprecated alias of StacksNodeApi.getCoreInfo, kept for backwards compatibility */ + /** @deprecated Kept for backwards compatibility, may be removed in the future */ getCoreInfo(): Promise { return this.client.fetch(`${this.client.baseUrl}/v2/info`).then(res => res.json()); } - /** @deprecated alias of StacksNodeApi.getPoxInfo, kept for backwards compatibility */ + /** @deprecated Kept for backwards compatibility, may be removed in the future */ getPoxInfo(): Promise { return this.client.fetch(`${this.client.baseUrl}/v2/pox`).then(res => res.json()); } - /** @deprecated alias of StacksNodeApi.getTargetBlockTime, kept for backwards compatibility */ + /** @deprecated Kept for backwards compatibility, may be removed in the future */ async getTargetBlockTime(): Promise { const res = await this.client .fetch(`${this.client.baseUrl}/extended/v1/info/network_block_times`) diff --git a/packages/stacking/tests/stacking-2.4.test.ts b/packages/stacking/tests/stacking-2.4.test.ts index 180924356..29ecaa7dd 100644 --- a/packages/stacking/tests/stacking-2.4.test.ts +++ b/packages/stacking/tests/stacking-2.4.test.ts @@ -1,5 +1,4 @@ -import { StacksNodeApi } from '@stacks/api'; -import { hexToBytes } from '@stacks/common'; +import { defaultClientOpts, hexToBytes } from '@stacks/common'; import { MOCK_EMPTY_ACCOUNT, MOCK_FULL_ACCOUNT, @@ -53,8 +52,11 @@ describe('2.4 activation', () => { '/v2/pox': `{"contract_id":"ST000000000000000000002AMW42H.pox-3","pox_activation_threshold_ustx":600057388429055,"first_burnchain_block_height":0,"current_burnchain_block_height":180,"prepare_phase_block_length":1,"reward_phase_block_length":4,"reward_slots":8,"rejection_fraction":3333333333333333,"total_liquid_supply_ustx":60005738842905576,"current_cycle":{"id":35,"min_threshold_ustx":1875180000000000,"stacked_ustx":1875180000000000,"is_pox_active":false},"next_cycle":{"id":36,"min_threshold_ustx":1875180000000000,"min_increment_ustx":7500717355363,"stacked_ustx":1875180000000000,"prepare_phase_start_block_height":184,"blocks_until_prepare_phase":4,"reward_phase_start_block_height":185,"blocks_until_reward_phase":5,"ustx_until_pox_rejection":8484139029839119000},"min_amount_ustx":1875180000000000,"prepare_cycle_length":1,"reward_cycle_id":35,"reward_cycle_length":5,"rejection_votes_left_required":8484139029839119000,"next_reward_cycle_in":5,"contract_versions":[{"contract_id":"ST000000000000000000002AMW42H.pox","activation_burnchain_block_height":0,"first_reward_cycle_id":0},{"contract_id":"ST000000000000000000002AMW42H.pox-2","activation_burnchain_block_height":107,"first_reward_cycle_id":22},{"contract_id":"ST000000000000000000002AMW42H.pox-3","activation_burnchain_block_height":111,"first_reward_cycle_id":23}]}`, }); - const api = new StacksNodeApi({ url: API_URL }); - const client = new StackingClient({ address: '', network: STACKS_TESTNET, api }); + const client = new StackingClient({ + address: '', + network: STACKS_TESTNET, + client: defaultClientOpts({ baseUrl: API_URL }), + }); const poxInfo = await client.getPoxInfo(); expect(poxInfo.contract_id).toBe('ST000000000000000000002AMW42H.pox-3'); @@ -77,8 +79,11 @@ test('in period 3, pox-3 stacking works', async () => { const address = 'STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6'; const poxAddress = '1Xik14zRm29UsyS6DjhYg4iZeZqsDa8D3'; - const api = new StacksNodeApi({ url: API_URL }); - const client = new StackingClient({ address, network: STACKS_TESTNET, api }); + const client = new StackingClient({ + address, + network: STACKS_TESTNET, + client: defaultClientOpts({ baseUrl: API_URL }), + }); setApiMocks({ '/v2/pox': `{"contract_id":"ST000000000000000000002AMW42H.pox-3","pox_activation_threshold_ustx":600057529871055,"first_burnchain_block_height":0,"current_burnchain_block_height":217,"prepare_phase_block_length":1,"reward_phase_block_length":4,"reward_slots":8,"rejection_fraction":3333333333333333,"total_liquid_supply_ustx":60005752987105576,"current_cycle":{"id":43,"min_threshold_ustx":1875180000000000,"stacked_ustx":0,"is_pox_active":false},"next_cycle":{"id":44,"min_threshold_ustx":1875180000000000,"min_increment_ustx":7500719123388,"stacked_ustx":0,"prepare_phase_start_block_height":219,"blocks_until_prepare_phase":2,"reward_phase_start_block_height":220,"blocks_until_reward_phase":3,"ustx_until_pox_rejection":1485692420695552500},"min_amount_ustx":1875180000000000,"prepare_cycle_length":1,"reward_cycle_id":43,"reward_cycle_length":5,"rejection_votes_left_required":1485692420695552500,"next_reward_cycle_in":3,"contract_versions":[{"contract_id":"ST000000000000000000002AMW42H.pox","activation_burnchain_block_height":0,"first_reward_cycle_id":0},{"contract_id":"ST000000000000000000002AMW42H.pox-2","activation_burnchain_block_height":107,"first_reward_cycle_id":22},{"contract_id":"ST000000000000000000002AMW42H.pox-3","activation_burnchain_block_height":111,"first_reward_cycle_id":23}]}`, @@ -122,8 +127,11 @@ describe('stacking eligibility', () => { const address = 'STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6'; const poxAddress = '1Xik14zRm29UsyS6DjhYg4iZeZqsDa8D3'; - const api = new StacksNodeApi({ url: API_URL }); - const client = new StackingClient({ address, network: STACKS_TESTNET, api }); + const client = new StackingClient({ + address, + network: STACKS_TESTNET, + client: defaultClientOpts({ baseUrl: API_URL }), + }); const cycles = 1; const stackingEligibility = await client.canStack({ poxAddress, cycles }); @@ -141,8 +149,11 @@ describe('stacking eligibility', () => { const address = 'ST162GBCTD9ESBF09XC2T63NCX6ZKS42ZPWGXZ6VH'; const poxAddress = 'mnTdnFyjxRomWaSLp4fNGSa9Gyg9XJo4j4'; - const api = new StacksNodeApi({ url: API_URL }); - const client = new StackingClient({ address, network: STACKS_TESTNET, api }); + const client = new StackingClient({ + address, + network: STACKS_TESTNET, + client: defaultClientOpts({ baseUrl: API_URL }), + }); const cycles = 1; const stackingEligibility = await client.canStack({ poxAddress, cycles }); @@ -162,8 +173,11 @@ describe('normal stacking', () => { const address = 'STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6'; const poxAddress = '1Xik14zRm29UsyS6DjhYg4iZeZqsDa8D3'; - const api = new StacksNodeApi({ url: API_URL }); - const client = new StackingClient({ address, network: STACKS_TESTNET, api }); + const client = new StackingClient({ + address, + network: STACKS_TESTNET, + client: defaultClientOpts({ baseUrl: API_URL }), + }); setApiMocks({ ...MOCK_POX_3_REGTEST, @@ -199,8 +213,11 @@ describe('normal stacking', () => { const address = 'STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6'; const poxAddress = '1Xik14zRm29UsyS6DjhYg4iZeZqsDa8D3'; - const api = new StacksNodeApi({ url: API_URL }); - const client = new StackingClient({ address, network: STACKS_TESTNET, api }); + const client = new StackingClient({ + address, + network: STACKS_TESTNET, + client: defaultClientOpts({ baseUrl: API_URL }), + }); setApiMocks({ ...MOCK_POX_3_REGTEST, @@ -254,8 +271,11 @@ describe('normal stacking', () => { const address = 'STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6'; const poxAddress = '1Xik14zRm29UsyS6DjhYg4iZeZqsDa8D3'; - const api = new StacksNodeApi({ url: API_URL }); - const client = new StackingClient({ address, network: STACKS_TESTNET, api }); + const client = new StackingClient({ + address, + network: STACKS_TESTNET, + client: defaultClientOpts({ baseUrl: API_URL }), + }); setApiMocks({ ...MOCK_POX_3_REGTEST, @@ -308,8 +328,11 @@ describe('delegated stacking', () => { const delegateTo = 'ST2MCYPWTFMD2MGR5YY695EJG0G1R4J2BTJPRGM7H'; - const api = new StacksNodeApi({ url: API_URL }); - const client = new StackingClient({ address, network: STACKS_TESTNET, api }); + const client = new StackingClient({ + address, + network: STACKS_TESTNET, + client: defaultClientOpts({ baseUrl: API_URL }), + }); setApiMocks({ ...MOCK_POX_3_REGTEST, @@ -350,8 +373,11 @@ describe('delegated stacking', () => { const delegateTo = 'ST2MCYPWTFMD2MGR5YY695EJG0G1R4J2BTJPRGM7H'; - const api = new StacksNodeApi({ url: API_URL }); - const client = new StackingClient({ address, network: STACKS_TESTNET, api }); + const client = new StackingClient({ + address, + network: STACKS_TESTNET, + client: defaultClientOpts({ baseUrl: API_URL }), + }); setApiMocks({ ...MOCK_POX_3_REGTEST, @@ -391,8 +417,11 @@ describe('delegated stacking', () => { const delegatorAddress = 'ST11NJTTKGVT6D1HY4NJRVQWMQM7TVAR091EJ8P2Y'; const delegatorPoxAddress = '1797Pp1o8A7a8X8Qs7ejXtYyw8gbecFK2b'; - const api = new StacksNodeApi({ url: API_URL }); - const client = new StackingClient({ address, network: STACKS_TESTNET, api }); + const client = new StackingClient({ + address, + network: STACKS_TESTNET, + client: defaultClientOpts({ baseUrl: API_URL }), + }); const delegatorClient = new StackingClient({ address: delegatorAddress, network: STACKS_TESTNET, @@ -457,8 +486,11 @@ describe('delegated stacking', () => { const delegatorAddress = 'ST11NJTTKGVT6D1HY4NJRVQWMQM7TVAR091EJ8P2Y'; const delegatorPoxAddress = '1797Pp1o8A7a8X8Qs7ejXtYyw8gbecFK2b'; - const api = new StacksNodeApi({ url: API_URL }); - const client = new StackingClient({ address, network: STACKS_TESTNET, api }); + const client = new StackingClient({ + address, + network: STACKS_TESTNET, + client: defaultClientOpts({ baseUrl: API_URL }), + }); const delegatorClient = new StackingClient({ address: delegatorAddress, network: STACKS_TESTNET, @@ -545,8 +577,11 @@ describe('delegated stacking', () => { const delegatorAddress = 'ST11NJTTKGVT6D1HY4NJRVQWMQM7TVAR091EJ8P2Y'; const delegatorPoxAddress = '1797Pp1o8A7a8X8Qs7ejXtYyw8gbecFK2b'; - const api = new StacksNodeApi({ url: API_URL }); - const client = new StackingClient({ address, network: STACKS_TESTNET, api }); + const client = new StackingClient({ + address, + network: STACKS_TESTNET, + client: defaultClientOpts({ baseUrl: API_URL }), + }); const delegatorClient = new StackingClient({ address: delegatorAddress, network: STACKS_TESTNET, @@ -632,20 +667,32 @@ describe('delegated stacking', () => { // * The pool commits a total stacking amount (covering all of its stackers) // * This is required for a pools pox-address to be "commited" into the reward-set - const api = new StacksNodeApi({ url: API_URL }); + const client = defaultClientOpts({ baseUrl: API_URL }); const stackerAKey = 'cb3df38053d132895220b9ce471f6b676db5b9bf0b4adefb55f2118ece2478df01'; const stackerAAddress = 'STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6'; - const clientA = new StackingClient({ address: stackerAAddress, network: STACKS_TESTNET, api }); + const clientA = new StackingClient({ + address: stackerAAddress, + network: STACKS_TESTNET, + client, + }); const stackerBKey = 'c71700b07d520a8c9731e4d0f095aa6efb91e16e25fb27ce2b72e7b698f8127a01'; const stackerBAddress = 'ST1HB1T8WRNBYB0Y3T7WXZS38NKKPTBR3EG9EPJKR'; - const clientB = new StackingClient({ address: stackerBAddress, network: STACKS_TESTNET, api }); + const clientB = new StackingClient({ + address: stackerBAddress, + network: STACKS_TESTNET, + client, + }); const poolPrivateKey = '21d43d2ae0da1d9d04cfcaac7d397a33733881081f0b2cd038062cf0ccbb752601'; const poolAddress = 'ST11NJTTKGVT6D1HY4NJRVQWMQM7TVAR091EJ8P2Y'; const poolPoxAddress = '1797Pp1o8A7a8X8Qs7ejXtYyw8gbecFK2b'; - const clientPool = new StackingClient({ address: poolAddress, network: STACKS_TESTNET, api }); + const clientPool = new StackingClient({ + address: poolAddress, + network: STACKS_TESTNET, + client, + }); setApiMocks({ ...MOCK_POX_3_REGTEST, @@ -697,7 +744,7 @@ describe('delegated stacking', () => { poxInfo = await clientPool.getPoxInfo(); // Manual nonce setting is required for multiple transactions in the same block - let noncePool = await fetchNonce({ address: poolAddress, api }); + let noncePool = await fetchNonce({ address: poolAddress, client }); // Pool stacks for stacker A const stackAPool = await clientPool.delegateStackStx({ @@ -785,20 +832,32 @@ describe('delegated stacking', () => { // * The pool realizes the mistake and increases the amount to all of its stackers' funds // * This will only work if the reward cycle anchor block hasn't been reached yet! - const api = new StacksNodeApi({ url: API_URL }); + const clientOpts = defaultClientOpts({ baseUrl: API_URL }); const stackerAKey = 'cb3df38053d132895220b9ce471f6b676db5b9bf0b4adefb55f2118ece2478df01'; const stackerAAddress = 'STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6'; - const clientA = new StackingClient({ address: stackerAAddress, network: STACKS_TESTNET, api }); + const clientA = new StackingClient({ + address: stackerAAddress, + network: STACKS_TESTNET, + client: clientOpts, + }); const stackerBKey = 'c71700b07d520a8c9731e4d0f095aa6efb91e16e25fb27ce2b72e7b698f8127a01'; const stackerBAddress = 'ST1HB1T8WRNBYB0Y3T7WXZS38NKKPTBR3EG9EPJKR'; - const clientB = new StackingClient({ address: stackerBAddress, network: STACKS_TESTNET, api }); + const clientB = new StackingClient({ + address: stackerBAddress, + network: STACKS_TESTNET, + client: clientOpts, + }); const poolPrivateKey = '21d43d2ae0da1d9d04cfcaac7d397a33733881081f0b2cd038062cf0ccbb752601'; const poolAddress = 'ST11NJTTKGVT6D1HY4NJRVQWMQM7TVAR091EJ8P2Y'; const poolPoxAddress = '1797Pp1o8A7a8X8Qs7ejXtYyw8gbecFK2b'; - const clientPool = new StackingClient({ address: poolAddress, network: STACKS_TESTNET, api }); + const clientPool = new StackingClient({ + address: poolAddress, + network: STACKS_TESTNET, + client: clientOpts, + }); setApiMocks({ ...MOCK_POX_3_REGTEST, @@ -847,7 +906,7 @@ describe('delegated stacking', () => { poxInfo = await clientPool.getPoxInfo(); // Manual nonce setting is required for multiple transactions in the same block - let noncePool = await fetchNonce({ address: poolAddress, api }); + let noncePool = await fetchNonce({ address: poolAddress, client: clientOpts }); // Pool stacks for stacker A (stacks all 3/4) const stackAPool = await clientPool.delegateStackStx({ @@ -959,8 +1018,11 @@ describe('btc addresses', () => { const privateKey = 'cb3df38053d132895220b9ce471f6b676db5b9bf0b4adefb55f2118ece2478df01'; const address = 'STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6'; - const api = new StacksNodeApi({ url: API_URL }); - const client = new StackingClient({ address, network: STACKS_TESTNET, api }); + const client = new StackingClient({ + address, + network: STACKS_TESTNET, + client: defaultClientOpts({ baseUrl: API_URL }), + }); setApiMocks({ ...MOCK_POX_3_REGTEST, diff --git a/packages/stacking/tests/stacking.test.ts b/packages/stacking/tests/stacking.test.ts index cdcd0299b..f547f391f 100644 --- a/packages/stacking/tests/stacking.test.ts +++ b/packages/stacking/tests/stacking.test.ts @@ -1,8 +1,14 @@ import { sha256 } from '@noble/hashes/sha256'; -import { StacksNodeApi } from '@stacks/api'; -import { HIRO_TESTNET_URL, bigIntToBytes, bytesToHex, hexToBytes } from '@stacks/common'; +import { + HIRO_TESTNET_URL, + bigIntToBytes, + bytesToHex, + defaultClientOpts, + hexToBytes, +} from '@stacks/common'; import { base58CheckDecode, getPublicKeyFromPrivate } from '@stacks/encryption'; -import { STACKS_MAINNET, STACKS_TESTNET } from '@stacks/network'; +import { V2_POX_REGTEST_POX_3, setApiMocks } from '@stacks/internal'; +import { STACKS_MAINNET, STACKS_TESTNET, defaultUrlFromNetwork } from '@stacks/network'; import { ClarityType, ReadOnlyFunctionOptions, @@ -22,7 +28,6 @@ import { validateContractCall, } from '@stacks/transactions'; import fetchMock from 'jest-fetch-mock'; -import { V2_POX_REGTEST_POX_3, setApiMocks } from '../../internal/src'; import { StackingClient } from '../src'; import { PoXAddressVersion, StackingErrors } from '../src/constants'; import { @@ -336,14 +341,25 @@ test('stack stx', async () => { validateWithAbi: true, network, senderKey: privateKey, - client, + client: expect.objectContaining({ + baseUrl: defaultUrlFromNetwork(network), + }), }; expect(fetchMock.mock.calls[0][0]).toEqual(`${HIRO_TESTNET_URL}/v2/pox`); expect(makeContractCall).toHaveBeenCalledTimes(1); - expect(makeContractCall).toHaveBeenCalledWith(expectedContractCallOptions); + expect(makeContractCall).toHaveBeenCalledWith( + expect.objectContaining(expectedContractCallOptions) + ); expect(broadcastTransaction).toHaveBeenCalledTimes(1); - expect(broadcastTransaction).toHaveBeenCalledWith({ transaction, client }); + expect(broadcastTransaction).toHaveBeenCalledWith( + expect.objectContaining({ + transaction, + client: expect.objectContaining({ + baseUrl: defaultUrlFromNetwork(network), + }), + }) + ); expect(stackingResults).toEqual(broadcastResponse); expect(isPoxAbiValid(expectedContractCallOptions)).toBe(true); }); @@ -408,14 +424,25 @@ test('delegate stx', async () => { validateWithAbi: true, network, senderKey: privateKey, - client, + client: expect.objectContaining({ + baseUrl: defaultUrlFromNetwork(network), + }), }; expect(fetchMock.mock.calls[0][0]).toEqual(`${HIRO_TESTNET_URL}/v2/pox`); expect(makeContractCall).toHaveBeenCalledTimes(1); - expect(makeContractCall).toHaveBeenCalledWith(expectedContractCallOptions); + expect(makeContractCall).toHaveBeenCalledWith( + expect.objectContaining(expectedContractCallOptions) + ); expect(broadcastTransaction).toHaveBeenCalledTimes(1); - expect(broadcastTransaction).toHaveBeenCalledWith({ transaction, client }); + expect(broadcastTransaction).toHaveBeenCalledWith( + expect.objectContaining({ + transaction, + client: expect.objectContaining({ + baseUrl: defaultUrlFromNetwork(network), + }), + }) + ); expect(delegateResults).toEqual(broadcastResponse); expect(isPoxAbiValid(expectedContractCallOptions)).toBe(true); }); @@ -472,14 +499,25 @@ test('delegate stx with empty optional parameters', async () => { validateWithAbi: true, network, senderKey: privateKey, - client, + client: expect.objectContaining({ + baseUrl: defaultUrlFromNetwork(network), + }), }; expect(fetchMock.mock.calls[0][0]).toEqual(`${HIRO_TESTNET_URL}/v2/pox`); expect(makeContractCall).toHaveBeenCalledTimes(1); - expect(makeContractCall).toHaveBeenCalledWith(expectedContractCallOptions); + expect(makeContractCall).toHaveBeenCalledWith( + expect.objectContaining(expectedContractCallOptions) + ); expect(broadcastTransaction).toHaveBeenCalledTimes(1); - expect(broadcastTransaction).toHaveBeenCalledWith({ transaction, client }); + expect(broadcastTransaction).toHaveBeenCalledWith( + expect.objectContaining({ + transaction, + client: expect.objectContaining({ + baseUrl: defaultUrlFromNetwork(network), + }), + }) + ); expect(delegateResults).toEqual(broadcastResponse); expect(isPoxAbiValid(expectedContractCallOptions)).toBe(true); }); @@ -555,14 +593,25 @@ test('delegate stack stx with one delegator', async () => { validateWithAbi: true, network, senderKey: privateKey, - client, + client: expect.objectContaining({ + baseUrl: defaultUrlFromNetwork(network), + }), }; expect(fetchMock.mock.calls[0][0]).toEqual(`${HIRO_TESTNET_URL}/v2/pox`); expect(makeContractCall).toHaveBeenCalledTimes(1); - expect(makeContractCall).toHaveBeenCalledWith(expectedContractCallOptions); + expect(makeContractCall).toHaveBeenCalledWith( + expect.objectContaining(expectedContractCallOptions) + ); expect(broadcastTransaction).toHaveBeenCalledTimes(1); - expect(broadcastTransaction).toHaveBeenCalledWith({ transaction, client }); + expect(broadcastTransaction).toHaveBeenCalledWith( + expect.objectContaining({ + transaction, + client: expect.objectContaining({ + baseUrl: defaultUrlFromNetwork(network), + }), + }) + ); expect(delegateResults).toEqual(broadcastResponse); expect(isPoxAbiValid(expectedContractCallOptions)).toBe(true); }); @@ -641,14 +690,25 @@ test('delegate stack stx with set nonce', async () => { network, senderKey: privateKey, nonce, - client, + client: expect.objectContaining({ + baseUrl: defaultUrlFromNetwork(network), + }), }; expect(fetchMock.mock.calls[0][0]).toEqual(`${HIRO_TESTNET_URL}/v2/pox`); expect(makeContractCall).toHaveBeenCalledTimes(1); - expect(makeContractCall).toHaveBeenCalledWith(expectedContractCallOptions); + expect(makeContractCall).toHaveBeenCalledWith( + expect.objectContaining(expectedContractCallOptions) + ); expect(broadcastTransaction).toHaveBeenCalledTimes(1); - expect(broadcastTransaction).toHaveBeenCalledWith({ transaction, client }); + expect(broadcastTransaction).toHaveBeenCalledWith( + expect.objectContaining({ + transaction, + client: expect.objectContaining({ + baseUrl: defaultUrlFromNetwork(network), + }), + }) + ); expect(delegateResults).toEqual(broadcastResponse); expect(isPoxAbiValid(expectedContractCallOptions)).toBe(true); }); @@ -704,14 +764,25 @@ test('delegator commit', async () => { validateWithAbi: true, network, senderKey: privateKey, - client, + client: expect.objectContaining({ + baseUrl: defaultUrlFromNetwork(network), + }), }; expect(fetchMock.mock.calls[0][0]).toEqual(`${HIRO_TESTNET_URL}/v2/pox`); expect(makeContractCall).toHaveBeenCalledTimes(1); - expect(makeContractCall).toHaveBeenCalledWith(expectedContractCallOptions); + expect(makeContractCall).toHaveBeenCalledWith( + expect.objectContaining(expectedContractCallOptions) + ); expect(broadcastTransaction).toHaveBeenCalledTimes(1); - expect(broadcastTransaction).toHaveBeenCalledWith({ transaction, client }); + expect(broadcastTransaction).toHaveBeenCalledWith( + expect.objectContaining({ + transaction, + client: expect.objectContaining({ + baseUrl: defaultUrlFromNetwork(network), + }), + }) + ); expect(delegateResults).toEqual(broadcastResponse); expect(isPoxAbiValid(expectedContractCallOptions)).toBe(true); }); @@ -753,14 +824,25 @@ test('revoke delegate stx', async () => { validateWithAbi: true, network, senderKey: privateKey, - client, + client: expect.objectContaining({ + baseUrl: defaultUrlFromNetwork(network), + }), }; expect(fetchMock.mock.calls[0][0]).toEqual(`${HIRO_TESTNET_URL}/v2/pox`); expect(makeContractCall).toHaveBeenCalledTimes(1); - expect(makeContractCall).toHaveBeenCalledWith(expectedContractCallOptions); + expect(makeContractCall).toHaveBeenCalledWith( + expect.objectContaining(expectedContractCallOptions) + ); expect(broadcastTransaction).toHaveBeenCalledTimes(1); - expect(broadcastTransaction).toHaveBeenCalledWith({ transaction, client }); + expect(broadcastTransaction).toHaveBeenCalledWith( + expect.objectContaining({ + transaction, + client: expect.objectContaining({ + baseUrl: defaultUrlFromNetwork(network), + }), + }) + ); expect(revokeDelegateResults).toEqual(broadcastResponse); expect(isPoxAbiValid(expectedContractCallOptions)).toBe(true); }); @@ -820,11 +902,15 @@ test('get stacking status', async () => { functionName: 'get-stacker-info', functionArgs: [standardPrincipalCV(address)], senderAddress: address, - client, + client: expect.objectContaining({ + baseUrl: defaultUrlFromNetwork(network), + }), }; expect(fetchCallReadOnlyFunction).toHaveBeenCalledTimes(1); - expect(fetchCallReadOnlyFunction).toHaveBeenCalledWith(expectedReadOnlyFunctionCallOptions); + expect(fetchCallReadOnlyFunction).toHaveBeenCalledWith( + expect.objectContaining(expectedReadOnlyFunctionCallOptions) + ); expect(stackingStatus.stacked).toEqual(true); expect(stackingStatus.details.first_reward_cycle).toEqual(firstRewardCycle); @@ -1146,8 +1232,11 @@ test('client operations with contract principal stacker', () => { }); test('getSecondsUntilStackingDeadline', async () => { - const api = new StacksNodeApi({ url: 'http://localhost:3999' }); - const client = new StackingClient({ address: '', network: STACKS_MAINNET, api }); + const client = new StackingClient({ + address: '', + network: STACKS_MAINNET, + client: defaultClientOpts({ baseUrl: 'http://localhost:3999' }), + }); setApiMocks({ '/extended/v1/info/network_block_times': `{"testnet":{"target_block_time":120},"mainnet":{"target_block_time":600}}`, diff --git a/packages/stacking/tsconfig.build.json b/packages/stacking/tsconfig.build.json index 039ff6365..63c0bb7ce 100644 --- a/packages/stacking/tsconfig.build.json +++ b/packages/stacking/tsconfig.build.json @@ -8,9 +8,6 @@ "composite": true }, "references": [ - { - "path": "../api/tsconfig.build.json" - }, { "path": "../common/tsconfig.build.json" },