Skip to content

Commit

Permalink
feat!: Stacks.js v7.0.0 (#1520)
Browse files Browse the repository at this point in the history
* fix!: consolidate poxaddress return types

BREAKING CHANGE:
Convert `version` of PoXAddress from array to number.

* feat: cleanup common files

* refactor: update to correct import path

* feat!: update to new network object (#1623)

* feat: split network into object and api opts

* fix: update imports

---------

Co-authored-by: janniks <[email protected]>

* feat: add new api package

* fix: update remaining packages for api (#1625)

Co-authored-by: janniks <[email protected]>

* refactor: update other packages to new paradigm

* test: fix remaining packages

* chore: add jest config

* chore: resolve circular dependency

* build: update commitlint to allow longer content

* refactor!: change clarity types to be human readable

BREAKING CHANGE:
The `ClarityType` was changed to a readable string, from the previous Number type. This makes it easier to read and construct types when debugging.

* test: add clarity wire format tests

* docs: add migration docs

* docs: pr update

Co-authored-by: Hugo C <[email protected]>

* docs: pr update

Co-authored-by: Hugo C <[email protected]>

* docs: enumerate nets

* feat!: remove wrapped private key type

BREAKING CHANGE:
Remove wrapped `StacksPrivateKey` type in favor of simple type alias for string/Uint8Array.

* test: update bns tests

* chore: update cli (#1656)

Co-authored-by: janniks <[email protected]>

* feat!: Make serialize methods return hex-encoded strings, instead of bytes

* docs: update migration guide

* fix!: Remove legacy CLI methods

* refactor: decrease circular deps in tx package

* build: fix typedoc build

* ci: update pr version detetction

* fix!: Disable legacy triplesec support for mnemonic encryption

BREAKING CHANGE:
Support for encrypting/decrypting mnemonics using `triplesec` has been removed.

* feat: Remove optional anchor mode from transaction options (#1654)

Co-authored-by: janniks <[email protected]>

* ci: update canary publishing

* build: update lerna

* fix: Add `.bootAddress` to network objects

* chore: disable rule correctly

* chore: reduce guessing tx version

* refactor: add addressVersion to network object

* refactor: consolidate address types

* fix: Allow network name in more helper functions

* refactor: move types

* fix: Improve address helper functions

* refactor!: Rename message types

* refactor!: Make StacksTransaction.serialize() return a hex-string instead of bytes

* refactor!: Rename more types to use "Wire" suffix

* refactor!: Remove BN.js compatability

* feat!: Update post-condition representation to human readable types

* refactor: move internal wire types to reduce circular dependencies

* refactor: add internal package for reusing test and other helpers

* feat: Add postConditionToHex helper

* fix: Allow .appendOrigin to be used with unwrapped public key

* feat!: Rename networking/fetch methods to include `fetch` prefix

* fix: Consolidate `is` prefixed boolean methods

* chore: add comment

* feat: Add STX unit helper methods

* feat: Add `Address` namespace

* feat: Add origin post-condition principals

* refactor: minor updates

* fix!: Remove signed option for intToBigInt

* fix!: Move more helper functions to take network parameter

* feat: Reduce wrapping of types for public key appending

* refactor: Remove Serialize prefix from enum keys

* refactor!: Remove wrapper type for message signatures

* fix!: Compressing private key should ensure string format

* refactor: Fix build breaking refactor changes

* fix: Generate compressed private keys by default

* refactor: Add renamed `randomSeedPhrase` method

* refactor: Rename api to client and undo previous StacksNodeAPI changes

* refactor: Continue client rename

* test: Update to succeed tests

* ci: update canary releases

* fix: Remove legacy methods

* chore: update comments

* fix: Fix string parsing in structured signature decode

* chore: Fix example in comment

* refactor: Undo removal

* fix!: Switch to a network and client param solution

* chore: fix imports

* docs: Update migration file

* refactor: Minor refactoring to match common theme

* refactor: Rename make methods

* refactor: Deprecate wallet config

* refactor: Remove unneeded deserialize overloads

* refactor!: Update StacksTransaction constructor to options object

* refactor!: Rename StacksTransaction to StacksTransactionWire

* fix: Update post conditions input in transactions

* chore: add forgotten rename

* docs: Update migration guide

* refactor: Change getStxAddress to use network parameter

* refactor!: Update Cl.serialize to return string instead of bytes

---------

Co-authored-by: janniks <[email protected]>
Co-authored-by: Hugo C <[email protected]>
  • Loading branch information
3 people authored Oct 25, 2024
1 parent 626e1ca commit 8ce84a3
Show file tree
Hide file tree
Showing 165 changed files with 11,473 additions and 12,807 deletions.
2 changes: 1 addition & 1 deletion .github/.husky/commit-msg
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"

npx @commitlint/cli --extends @commitlint/config-conventional --edit "$1"
npx @commitlint/cli --config .github/.husky/commitlint.json --edit "$1"
15 changes: 15 additions & 0 deletions .github/.husky/commitlint.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"extends": ["@commitlint/config-conventional"],
"rules": {
"body-max-length": [0, "always"],
"body-max-line-length": [0, "always"],
"footer-max-length": [0, "always"],
"footer-max-line-length": [0, "always"],
"header-max-length": [0, "always"],
"scope-max-length": [0, "always"],
"subject-max-length": [0, "always"],
"type-max-length": [0, "always"],

"subject-case": [0, "always"]
}
}
320 changes: 319 additions & 1 deletion .github/MIGRATION.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,22 @@
# Migration Guides

- [Stacks.js (\<=4.x.x) → (5.x.x)](#stacksjs-4xx--5xx)
- [Stacks.js (\>=5.x.x) → (7.x.x)](#stacksjs-5xx--7xx)
- [Breaking Changes](#breaking-changes)
- [Reducing Wrapper Types](#reducing-wrapper-types)
- [Stacks Network](#stacks-network)
- [Impacts](#impacts)
- [Clarity Representation](#clarity-representation)
- [Post-conditions](#post-conditions)
- [Fetch Methods](#fetch-methods)
- [`serialize` methods](#serialize-methods)
- [Asset Helper Methods](#asset-helper-methods)
- [CLI](#cli)
- [Triplesec](#triplesec)
- [Advanced: WireType](#advanced-wiretype)
- [Advanced: Signed BigInt](#advanced-signed-bigint)
- [Advanced: Refactorings](#advanced-refactorings)
- [Stacks.js (\<=4.x.x) → (5.x.x)](#stacksjs-4xx--5xx)
- [Breaking Changes](#breaking-changes-1)
- [Buffer to Uint8Array](#buffer-to-uint8array)
- [Message Signing Prefix](#message-signing-prefix)
- [blockstack.js → Stacks.js (1.x.x)](#blockstackjs--stacksjs-1xx)
Expand All @@ -14,6 +29,309 @@
- [Using blockstack.js](#using-blockstackjs-2)
- [Using @stacks/encryption or @stacks/auth](#using-stacksencryption-or-stacksauth)

## Stacks.js (&gt;=5.x.x) → (7.x.x)

### Breaking Changes

- The `@stacks/network` `new StacksNetwork()` objects were removed. Instead `@stacks/network` now exports the objects `STACKS_MAINNET`, `STACKS_TESNET`, and `STACKS_DEVNET`, which are static (and shouldn't be changed for most use-cases). [Read more...](#stacks-network)
- Most `fetch` (aka networking) methods were renamed to indicate they send HTTP requests. The new methods are named `fetchXyz` and are compatible with the old `Xyz` interfaces. [Read more...](#fetch-methods)
- Reducing wrapper types, which create annoyances for the developer, rather than being able to use values directly. [Read more...](#reducing-wrapper-types)
- The `ClarityType` enum was replaced by a human-readable version. The previous (wire format compatible) enum is still available as `ClarityWireType`. [Read more...](#clarity-representation)
- The previous post-conditions types and `create..` methods were replaced with a human-readable representation. [Read more...](#post-conditions)
- `StacksTransaction.serialize` and other `serializeXyz` methods were changed to return `string` (hex-encoded) instead of `Uint8Array`. Compatible `serializeXzyBytes` methods were added to ease the migration. [Read more...](#serialize-methods)
- The `AssetInfo` type was renamed to `Asset` for accuracy. The `Asset` helper methods were also renamed to to remove the `Info` suffix. [Read more...](#asset-helper-methods)
- Remove legacy CLI methods. [Read more...](#cli)
- Disable legacy `triplesec` mnemonic encryption support. [Read more...](#triplesec)
- **Advanced:** Rename `MessageType` and related concepts to `WireType`. [Read more...](#advanced-wiretype)
- **Advanced:** Removes two's complement compatibilty from `intToBigInt` parser method. [Read more...](#advanced-signed-bigint)
- **Advanced:** Refactorings and less visible updates. [Read more...](#advanced-refactorings)

### Reducing Wrapper Types

With this release we are aiming to reduce unnecessary "wrapper" types, which are used in the internals of the codebase, but shouldn't be pushed onto the user/developer.

This breaks the signatures of many functions:

- `signMessageHashRsv`, `signWithKey` now return the message signature as a `string` directly.
- `nextSignature`, `nextVerification`, `publicKeyFromSignatureVrs`, `publicKeyFromSignatureRsv` now take in the message signature as a `string`.

### Stacks Network

From now on "network" objects are static (aka constants) and don't require instantiation.

The `@stacks/network` package exports the following network objects:

- `STACKS_MAINNET`
- `STACKS_TESTNET`
- `STACKS_DEVNET`
- `STACKS_MOCKNET` (alias for `STACKS_DEVNET`)

```ts
import { STACKS_MAINNET } from '@stacks/network';
import { STACKS_TESTNET } from '@stacks/network';
import { STACKS_DEVNET } from '@stacks/network';

console.log(STACKS_MAINNET);
// {
// chainId: 1,
// transactionVersion: 0,
// peerNetworkId: 385875968,
// magicBytes: 'X2',
// bootAddress: 'SP000000000000000000002Q6VF78',
// addressVersion: { singleSig: 22, multiSig: 20 },
// client: { baseUrl: 'https://api.mainnet.hiro.so' }
// }
```

After importing the network object (e.g. `STACKS_MAINNET` here), you can use it in other functions as the `network` parameter.
Most of the time it's easier to just set the `network` parameter to a string literal (`'mainnet'`, `'testnet'`, or `'devnet'`).

As part of the network object, the `client` property was added.
This contains a `baseUrl` property and can optionally contain a `fetch` property.

For easing the transition, the functions which depended on a network instance now accept an optional `client` parameter.
The `client` parameter can be any object containing a `baseUrl` and `fetch` property.

- The `baseUrl` property should be a string containing the base URL of the Stacks node you want to use.
- The `fetch` property can be any (fetch)[https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API] compatible function.

The following diffs show examples of how to migrate to the new pattern.

```diff
import { makeSTXTokenTransfer } from '@stacks/transactions';

- import { StacksTestnet } from '@stacks/network';
+ import { STACKS_TESTNET } from '@stacks/network';

const transaction = await makeSTXTokenTransfer({
// ...
- network: new StacksTestnet(),
+ network: STACKS_TESTNET,
});
```

> [!NOTE]
> String literal network names are still supported and the recommended way to specify the network.
```diff
const transaction = await makeSTXTokenTransfer({
// ...
- network: new StacksTestnet(),
+ network: 'testnet',
});
```

> [!NOTE]
> Custom URLs and fetch functions are still supported via the `client` parameter or via `network.client`.
```diff
const transaction = await makeSTXTokenTransfer({
// ...
- network: new StacksTestnet({ url: "mynode-optional.com", fetchFn: myFetch }), // optional options
+ network: STACKS_TESTNET,
+ client: { baseUrl: "mynode-optional.com", fetch: myFetch } // optional params
});
```

```diff
const transaction = await makeSTXTokenTransfer({
// ...
- network: new StacksTestnet({ url: "mynode-optional.com", fetchFn: myFetch }), // optional options
+ network: {
+ ...STACKS_TESTNET,
+ client: { baseUrl: "mynode-optional.com", fetch: myFetch } // optional params
+ },
});
```

#### Impacts

- @stacks/bns: `BnsContractAddress` was removed, since `.bootAddress` is now a part of the network objects.
- @stacks/transactions: `AddressVersion` was moved to `@stacks/network`.

### Clarity Representation

The `ClarityType` enum was replaced by a readable version.
The previous (wire format compatible) enum is still available as `ClarityWireType`.
These types are considered somewhat internal and shouldn't cause breaking changes for most use-cases.

The property holding the value of the data type is now called `value` in all cases.
Previously, there was a mix of `value`, `list`, `buffer` etc.
For `bigint` values, the type of the `value` property is a now `string`, for better serialization compatibility.

```diff
{
- type: 1,
+ type: "uint",
- value: 12n,
+ value: "12",
}
```

```diff
{
- type: 11,
+ type: "list",
- list: [ ... ],
+ value: [ ... ],
}
```

### Post-conditions

The old `PostCondition` type was renamed to `PostConditionWire`.
A new human-readable `PostCondition` type was introduced in its place.

Below is an example of the new `PostCondition` types.

```ts
// STX post-condition
const stxPostCondition: StxPostCondition = {
type: 'stx-postcondition',
address: 'SP2JXKMSH007NPYAQHKJPQMAQYAD90NQGTVJVQ02B',
condition: 'gte',
amount: '100',
};

// Fungible token post-condition
const ftPostCondition: FungiblePostCondition = {
type: 'ft-postcondition',
address: 'SP2JXKMSH007NPYAQHKJPQMAQYAD90NQGTVJVQ02B',
condition: 'eq',
amount: '100',
asset: 'SP3D6PV2ACBPEKYJTCMH7HEN02KP87QSP8KTEH335.my-ft-token::my-token',
};

// Non-fungible token post-condition
const nftPostCondition: NonFungiblePostCondition = {
type: 'nft-postcondition',
address: 'SP2JXKMSH007NPYAQHKJPQMAQYAD90NQGTVJVQ02B',
condition: 'sent',
asset: 'SP3D6PV2ACBPEKYJTCMH7HEN02KP87QSP8KTEH335.my-nft::my-asset',
assetId: Cl.uint(602),
};
```

### Fetch Methods

The following methods were renamed:

- `estimateFee``fetchFeeEstimate`
- `estimateTransfer``fetchFeeEstimateTransfer`
- `estimateTransaction``fetchFeeEstimateTransaction`
- `getAbi``fetchAbi`
- `getNonce``fetchNonce`
- `getContractMapEntry``fetchContractMapEntry`
- `callReadOnlyFunction``fetchCallReadOnlyFunction`

`broadcastTransaction` wasn't renamed to highlight the uniqueness of the method.
Namely, the node/API it is sent to will "broadcast" the transaction to the mempool.

### `serialize` methods

Most users shouldn't need to use `serializeXyz` methods.
Concepts in Stacks.js have helpers like `postConditionToHex` instead.
Serialization is meant for internal representations in transactions, mostly not for user-facing data.

Existing methods now take or return **hex-encoded strings** _instead_ of `Uint8Array`s.

> If you were already converting returned bytes to hex-strings in your code, you can now skip the conversion step — hex-strings are the new default.
For easier migrating, renaming the following methods is possible to keep the previous behavior:

- `StacksTransaction.serialize``StacksTransaction.serializeBytes`
- `serializeAddress``serializeAddressBytes`
- `serializeAuthorization``serializeAuthorizationBytes`
- `serializeCV``serializeCVBytes`
- `serializeLPList``serializeLPListBytes`
- `serializeLPString``serializeLPStringBytes`
- `serializeMemoString``serializeMemoStringBytes`
- `serializeMessageSignature``serializeMessageSignatureBytes`
- `serializeMultiSigSpendingCondition``serializeMultiSigSpendingConditionBytes`
- `serializePayload``serializePayloadBytes`
- `serializePostCondition``serializePostConditionBytes`
- `serializePublicKey``serializePublicKeyBytes`
- `serializeSingleSigSpendingCondition``serializeSingleSigSpendingConditionBytes`
- `serializeSpendingCondition``serializeSpendingConditionBytes`
- `serializeStacksMessage``serializeStacksMessageBytes`
- `serializeStacksMessage``serializeStacksWireBytes`
- `serializeTransactionAuthField``serializeTransactionAuthFieldBytes`

### Asset Helper Methods

The following interfaces and methods were renamed:

- `AssetInfo``Asset`
- `StacksWireType.AssetInfo``StacksWireType.Asset`
- `createAssetInfo``createAsset`
- `parseAssetInfoString``parseAssetString`

### CLI

- Removed the `authenticator` method for legacy Blockstack authentication.

### Triplesec

Support for encrypting/decrypting mnemonics with `triplesec` was removed.
This impacts the methods: `decrypt`, `decryptMnemonic`, and `decryptLegacy`.
Make sure to update your code to if mnemonics are stored somewhere encrypted using the legacy method.

### Advanced: WireType

Renamed internals to avoid confusion between "message" and wire-format for serialization.
This is only used for advanced serialization use-cases internally and should not be needed for most users.

- `StacksMessage``StacksWire`
- `StacksMessageType``StacksWireType`
- `serializeStacksMessage``serializeStacksWireBytes`

More types were renamed to indicate use for serialization to _wire-format_:

- `MessageSignature``MessageSignatureWire`
- `StacksPublicKey``PublicKeyWire`
- `TransactionAuthField``TransactionAuthFieldWire`
- `Asset``AssetWire`
- `Address``AddressWire`
- `PostCondition``PostConditionWire`
- `PostConditionPrincipal``PostConditionPrincipalWire`
- `STXPostCondition``STXPostConditionWire`
- `FungiblePostCondition``FungiblePostConditionWire`
- `NonFungiblePostCondition``NonFungiblePostConditionWire`
- `LengthPrefixedString``LengthPrefixedStringWire`
- `CoinbasePayload``CoinbasePayloadWire`
- `PoisonPayload``PoisonPayloadWire`
- `SmartContractPayload``SmartContractPayloadWire`
- `TokenTransferPayload``TokenTransferPayloadWire`
- `VersionedSmartContractPayload``VersionedSmartContractPayloadWire`
- `NakamotoCoinbasePayload``NakamotoCoinbasePayloadWire`
- `TenureChangePayload``TenureChangePayloadWire`
- `StandardPrincipal``StandardPrincipalWire`
- `ContractPrincipal``ContractPrincipalWire`

### Advanced: Signed BigInt

The `intToBigInt` method no longer supports two's complement signed integers and removed the `signed` boolean parameter.
This likely was a misunderstood and unused feature.

### Advanced: Refactorings

- The `StacksTransaction` was renamed to `StacksTransactionWire` and its class constructor was updated to take in an options object instead of individual parameters. In the future a new `StacksTransaction` may be introduced to replace it, with more human-readable properties.
- `postConditionMode` now also accepts string literals: `'deny'`, `'allow'` (in addition to the imported `PostConditionMode` enum).
- `anchorMode` and related items were deprecated, since they no longer change behavior on-chain.
- `pubKeyfromPrivKey` was renamed `privateKeyToPublic`
- `encodeStructuredData` now returns a hex-encoded string instead of a Uint8Array (use `encodeStructuredDataBytes` if you need the raw bytes).
- `decodeStructuredDataSignature` now returns a hex-encoded string instead of a Uint8Array (use `decodeStructuredDataSignatureBytes` if you need the raw bytes). Also fixes a bug that previously tried to parse input strings as UTF-8 bytes instead of hex-encoded strings.
- `hashStructuredData` now returns a hex-encoded string instead of a Uint8Array (use `hashStructuredDataBytes` if you need the raw bytes).
- `AddressHashMode`: The `Serialize` prefixes were removed for brevity.
- `makeRandomPrivKey` was renamed to `randomPrivateKey` and now returns a compressed private key.
- `generateSecretKey` was renamed to `randomSeedPhrase`.
- `nextYear`, `nextMonth`, `nextHour`, `makeUUID4`, `updateQueryStringParameter`, `getAesCbcOutputLength`, `getAPIUsageErrorMessage`, `isSameOriginAbsoluteUrl`, `isLaterVersion`, `getBase64OutputLength`, were marked as deprecated.
- `encrypt` and `decrypt` in `@stacks/wallet-sdk` (aliases of `encryptMnemonic` and `decryptMnemonic` in the `@stacks/encryption` package respectively) were removed.
- `makeECPrivateKey` in `@stacks/encryption` was deprecated, use `randomPrivateKey` instead.
- `makeSigHashPreSign` was renamed to `sigHashPreSign` and marked as internal.
- `makeSigHashPostSign` was renamed to `sigHashPostSign` and marked as internal.
- `@stacks/wallet-sdk` `WalletConfig` types and helpers were marked as deprecated.

## Stacks.js (&lt;=4.x.x) → (5.x.x)

### Breaking Changes
Expand Down
Loading

0 comments on commit 8ce84a3

Please sign in to comment.