Skip to content

Commit 897c261

Browse files
authored
Merge pull request #952 from hirosystems/develop
update stacks.js content and code examples
2 parents 12f4389 + 499ac40 commit 897c261

11 files changed

+147
-127
lines changed

content/docs/stacks/stacks.js/concepts/accounts-and-addresses.mdx

+5-4
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ Testnet: `ST2F4BK4GZH6YFBNHYDDGN4T1RKBA7DA1BJZPJEJJ`
1515

1616
### Using Stacks Connect
1717

18-
```ts
18+
```tsx -n
1919
import { showConnect } from '@stacks/connect';
2020

2121
showConnect({
@@ -31,8 +31,9 @@ showConnect({
3131

3232
### Using a seed phrase / mnemonic / private key
3333

34-
```ts
35-
import { randomSeedPhrase, generateWallet, privateKeyToAddress } from "@stacks/wallet-sdk";
34+
```ts -n
35+
import { randomSeedPhrase, generateWallet } from "@stacks/wallet-sdk";
36+
import { privateKeyToAddress } from "@stacks/transactions";
3637

3738
const seed = randomSeedPhrase();
3839

@@ -47,7 +48,7 @@ const address = privateKeyToAddress(wallet.accounts[0].stxPrivateKey, 'mainnet')
4748

4849
### Using a public key
4950

50-
```ts
51+
```ts -n
5152
import { publicKeyToAddress } from '@stacks/transactions';
5253

5354
const address = publicKeyToAddress(publicKey, 'mainnet');

content/docs/stacks/stacks.js/concepts/broadcasting.mdx

+11-11
Original file line numberDiff line numberDiff line change
@@ -7,19 +7,19 @@ description: Learn how to broadcast transactions to the Stacks network.
77

88
A finalized transaction can be broadcasted to the network or serialized (to a byte representation) using Stacks.js.
99

10-
```ts
11-
import { bytesToHex } from '@stacks/common';
12-
import {
13-
makeSTXTokenTransfer,
14-
broadcastTransaction,
15-
AnchorMode,
16-
} from '@stacks/transactions';
10+
```ts -n
11+
import { broadcastTransaction, makeSTXTokenTransfer } from "@stacks/transactions";
1712

18-
const broadcastResponse = await broadcastTransaction(transaction);
19-
const txId = broadcastResponse.txid;
13+
const transaction = await makeSTXTokenTransfer({
14+
recipient: "ST1SJ3DTE5DN7X54YDH5D64R3BCB6A2AG2ZQ8YPD5",
15+
amount: 42000000,
16+
senderKey:
17+
"753b7cc01a1a2e86221266a154af739463fce51219d97e4f856cd7200c3bd2a601",
18+
network: "devnet",
19+
});
20+
21+
const tx = await broadcastTransaction({ transaction });
2022

21-
const serializedTx = tx.serialize();
22-
const serializedTxHex = bytesToHex(serializedTx);
2323
```
2424

2525
<Callout title="Info">For web applications, user wallets can broadcast transactions via [@stacks/connect](/stacks/connect).</Callout>

content/docs/stacks/stacks.js/concepts/post-conditions.mdx

+33-2
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,9 @@ More precisely, adding post-conditions to a transaction can ensure that:
1515
Post-conditions aren't perfect. They can't say anything about the end-state after a transaction. In other words, they can't guarantee the receipt of FTs/NFTs, since they only check for sending.
1616
</Callout>
1717

18-
Here's an example of a post-condition where the `principal` must send 1000 uSTX, or else the transaction will abort:
18+
Here's an example of a post-condition using the `Pc` helper, where the `principal` must send 1000 uSTX, or else the transaction will abort:
1919

20-
```js
20+
```ts -n
2121
import { Pc } from '@stacks/transactions';
2222

2323
const tx = await makeContractCall({
@@ -28,6 +28,37 @@ const tx = await makeContractCall({
2828
});
2929
```
3030

31+
If you prefer to write the post-condition manually, you can do so using the following approach:
32+
33+
```ts -n
34+
import { StxPostCondition, FungiblePostCondition, NonFungiblePostCondition } from '@stacks/transactions';
35+
// STX post-condition
36+
const stxPostCondition: StxPostCondition = {
37+
type: 'stx-postcondition',
38+
address: 'SP2JXKMSH007NPYAQHKJPQMAQYAD90NQGTVJVQ02B',
39+
condition: 'gte', // 'eq' | 'gt' | 'gte' | 'lt' | 'lte'
40+
amount: '100',
41+
};
42+
43+
// Fungible token post-condition
44+
const ftPostCondition: FungiblePostCondition = {
45+
type: 'ft-postcondition',
46+
address: 'SP2JXKMSH007NPYAQHKJPQMAQYAD90NQGTVJVQ02B',
47+
condition: 'eq', // 'eq' | 'gt' | 'gte' | 'lt' | 'lte'
48+
amount: '100',
49+
asset: 'SP3D6PV2ACBPEKYJTCMH7HEN02KP87QSP8KTEH335.my-ft-token::my-token',
50+
};
51+
52+
// Non-fungible token post-condition
53+
const nftPostCondition: NonFungiblePostCondition = {
54+
type: 'nft-postcondition',
55+
address: 'SP2JXKMSH007NPYAQHKJPQMAQYAD90NQGTVJVQ02B',
56+
condition: 'sent', // 'sent' | 'not-sent'
57+
asset: 'SP3D6PV2ACBPEKYJTCMH7HEN02KP87QSP8KTEH335.my-nft::my-asset',
58+
assetId: Cl.uint(602),
59+
};
60+
```
61+
3162
## Post-condition mode
3263

3364
In addition to the post-condition itself, we can also specify a `mode` for the transaction to verify asset transfers.

content/docs/stacks/stacks.js/concepts/private-keys.mdx

+18-20
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ Developers can build scripts, backends, and tools intended for full control over
3030
Let's start by generating a random private key.
3131
Note that this will return a different value each time you run the code.
3232

33-
```ts
33+
```ts -n
3434
import { randomPrivateKey } from '@stacks/transactions';
3535

3636
const privateKey = randomPrivateKey();
@@ -46,7 +46,7 @@ Typically, we don't want to generate random private keys, but instead use a dete
4646

4747
#### Generate a random seed phrase (24 words):
4848

49-
```ts
49+
```ts -n
5050
import { randomSeedPhrase } from '@stacks/wallet-sdk';
5151

5252
const phrase = randomSeedPhrase();
@@ -55,11 +55,13 @@ const phrase = randomSeedPhrase();
5555

5656
#### Generate a wallet from a seed phrase:
5757

58-
```ts
59-
import { generateWallet } from '@stacks/wallet-sdk';
58+
```ts -n
59+
import { generateWallet, randomSeedPhrase } from '@stacks/wallet-sdk';
6060

61-
let wallet = generateWallet({
62-
secretKey: seed,
61+
const seedPhrase = randomSeedPhrase();
62+
63+
let wallet = await generateWallet({
64+
secretKey: seedPhrase,
6365
password: "secret",
6466
});
6567

@@ -75,20 +77,16 @@ console.log(wallet.accounts[0]); // one account is generated by default
7577

7678
#### Generate more accounts:
7779

78-
```ts
79-
import { generateNewAccount } from '@stacks/wallet-sdk';
80-
81-
wallet = generateNewAccount(wallet);
82-
console.log(wallet.accounts.length); // 2
83-
```
80+
```ts -n
81+
import { generateNewAccount, generateWallet, randomSeedPhrase } from '@stacks/wallet-sdk';
8482

85-
### What else can we do with private keys?
83+
const seedPhrase = randomSeedPhrase();
8684

87-
<SmallCard
88-
icon={<FileSignature className='transition-colors duration-500 ease-in-out group-hover:text-primary' />}
89-
href="/stacks/stacks.js/guides/broadcast-transactions"
90-
title="Sign Transactions"
91-
description="Learn how to sign transactions with Stacks.js."
92-
/>
85+
let wallet = await generateWallet({
86+
secretKey: seedPhrase,
87+
password: "secret",
88+
});
9389

94-
{/* todo: add more links and guides: 1. encrypt/decrypt data, 2. create/verify signatures */}
90+
wallet = generateNewAccount(wallet);
91+
console.log(wallet.accounts.length); // 2
92+
```

content/docs/stacks/stacks.js/concepts/transactions.mdx

+3-7
Original file line numberDiff line numberDiff line change
@@ -9,16 +9,14 @@ The following shows how to create a simple transaction (STX transfer) using Stac
99

1010
### Using Stacks Connect
1111

12-
```ts
12+
```ts -n
1313
import { openSTXTransfer } from '@stacks/connect';
14-
import { AnchorMode } from '@stacks/transactions';
1514

1615
openSTXTransfer({
1716
network: 'testnet',
1817

1918
recipient: 'ST39MJ145BR6S8C315AG2BD61SJ16E208P1FDK3AK', // which address you are sending to
2019
amount: 10000, // tokens, denominated in micro-STX
21-
anchorMode: AnchorMode.Any,
2220

2321
onFinish: response => console.log(response.txid),
2422
onCancel: () => console.log('User canceled'),
@@ -30,16 +28,16 @@ openSTXTransfer({
3028
For full manual transaction signing, you need to provide the sender's private key.
3129
Treat the private key as a secret and *never* expose it to the public.
3230

33-
```ts
31+
```ts -n
3432
import { makeSTXTokenTransfer } from '@stacks/transactions';
3533

3634
const privateKey = randomPrivateKey(); // see "Private Keys & Wallets" page
3735

3836
const tx = await makeSTXTokenTransfer({
3937
recipient: 'ST39MJ145BR6S8C315AG2BD61SJ16E208P1FDK3AK', // which address you are sending to
4038
amount: 10000, // tokens, denominated in micro-STX
41-
anchorMode: 'any',
4239
senderKey: privateKey,
40+
network: "testnet",
4341
});
4442
```
4543

@@ -49,5 +47,3 @@ In Stacks.js, we can create transactions for different purposes:
4947
- STX token transfers
5048
- Smart contract calls
5149
- Smart contract deployments
52-
53-
{/* continue */}

content/docs/stacks/stacks.js/guides/broadcast-transactions.mdx

+26-37
Original file line numberDiff line numberDiff line change
@@ -58,17 +58,15 @@ There are three types of transactions:
5858
<TabsContent value="transfer">
5959
To transfer STX, use the `makeSTXTokenTransfer` function provided by the `@stacks/transactions` package:
6060

61-
```ts stx-transfer.ts
62-
import { AnchorMode, makeSTXTokenTransfer, broadcastTransaction } from "@stacks/transactions";
63-
import { StacksDevnet } from "@stacks/network";
61+
```ts stx-transfer.ts -cn
62+
import { broadcastTransaction, makeSTXTokenTransfer } from "@stacks/transactions";
6463

6564
const transaction = await makeSTXTokenTransfer({
6665
recipient: "SP3FGQ8Z7JY9BWYZ5WM53E0M9NK7WHJF0691NZ159",
6766
amount: 12345n,
6867
senderKey:
6968
"753b7cc01a1a2e86221266a154af739463fce51219d97e4f856cd7200c3bd2a601",
70-
network: new StacksDevnet(),
71-
anchorMode: AnchorMode.Any,
69+
network: "devnet",
7270
});
7371
```
7472

@@ -80,17 +78,15 @@ There are three types of transactions:
8078
<TabsContent value="deploy">
8179
To deploy a contract, use the `makeContractDeploy` function provided by the `@stacks/transactions` package:
8280

83-
```ts contract-deploy.ts
84-
import { makeContractDeploy, broadcastTransaction, AnchorMode } from '@stacks/transactions';
85-
import { StacksTestnet, StacksMainnet } from '@stacks/network';
81+
```ts contract-deploy.ts -cn
82+
import { broadcastTransaction, makeContractDeploy } from '@stacks/transactions';
8683

8784
const transaction = await makeContractDeploy({
8885
contractName: 'hello-world',
8986
codeBody: `(define-public (hello)
9087
(ok "Hello, world!"))`,
9188
senderKey: '753b7cc01a1a2e86221266a154af739463fce51219d97e4f856cd7200c3bd2a601',
92-
network: new StacksTestnet(),
93-
anchorMode: AnchorMode.Any,
89+
network: "testnet",
9490
});
9591
```
9692

@@ -102,36 +98,29 @@ There are three types of transactions:
10298
<TabsContent value="execute">
10399
To execute a contract function, use the `makeContractCall` function provided by the `@stacks/transactions` package:
104100

105-
```ts function-call.ts
101+
```ts function-call.ts -cn
106102
import {
107-
makeContractCall,
108103
broadcastTransaction,
109-
AnchorMode,
110-
FungibleConditionCode,
111-
makeStandardSTXPostCondition,
112104
bufferCVFromString,
113-
} from '@stacks/transactions';
114-
import { StacksTestnet, StacksMainnet } from '@stacks/network';
115-
116-
// Add an optional post condition
117-
// See below for details on constructing post conditions
118-
const postConditionAddress = 'SP2ZD731ANQZT6J4K3F5N8A40ZXWXC1XFXHVVQFKE';
119-
const postConditionCode = FungibleConditionCode.GreaterEqual;
120-
const postConditionAmount = 1000000n;
121-
const postConditions = [
122-
makeStandardSTXPostCondition(postConditionAddress, postConditionCode, postConditionAmount),
123-
];
105+
Cl,
106+
makeContractCall,
107+
Pc,
108+
} from "@stacks/transactions";
109+
110+
const postCondition = Pc.principal("SP2ZD731ANQZT6J4K3F5N8A40ZXWXC1XFXHVVQFKE")
111+
.willSendEq(1000000n)
112+
.ustx();
124113

125114
const transaction = await makeContractCall({
126-
contractAddress: 'SPBMRFRPPGCDE3F384WCJPK8PQJGZ8K9QKK7F59X',
127-
contractName: 'contract_name',
128-
functionName: 'contract_function',
129-
functionArgs: [bufferCVFromString('foo')],
130-
senderKey: 'b244296d5907de9864c0b0d51f98a13c52890be0404e83f273144cd5b9960eed01',
115+
contractAddress: "SPBMRFRPPGCDE3F384WCJPK8PQJGZ8K9QKK7F59X",
116+
contractName: "contract_name",
117+
functionName: "contract_function",
118+
functionArgs: [Cl.bufferFromAscii("foo")],
119+
senderKey:
120+
"b244296d5907de9864c0b0d51f98a13c52890be0404e83f273144cd5b9960eed01",
131121
validateWithAbi: true,
132-
network: new StacksTestnet(),
133-
postConditions,
134-
anchorMode: AnchorMode.Any,
122+
network: "testnet",
123+
postConditions: [postCondition],
135124
});
136125
```
137126

@@ -149,10 +138,10 @@ After building the transaction, broadcast it to the Stacks blockchain network us
149138
1. Pass in the transaction object you created in the previous step to the `broadcastTransaction` function.
150139
2. Handle the response by logging the response object.
151140

152-
```tsx
141+
```ts -cn
153142
import { broadcastTransaction } from '@stacks/transactions';
154143

155-
const broadcastResponse = await broadcastTransaction(transaction);
144+
const broadcastResponse = await broadcastTransaction({ transaction });
156145
```
157146

158147
This code sends the signed transaction to the Stacks blockchain. The `broadcastTransaction` function returns a response containing the transaction ID, which can be used to track the transaction on the blockchain.
@@ -161,7 +150,7 @@ This code sends the signed transaction to the Stacks blockchain. The `broadcastT
161150

162151
Handle the transaction results by checking the transaction status and responding accordingly.
163152

164-
```ts
153+
```ts -cn
165154
if (broadcastResponse.success) {
166155
console.log('Transaction successful with ID:', broadcastResponse.txid);
167156
} else {

content/docs/stacks/stacks.js/guides/post-conditions.mdx

+6-6
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ Post-conditions can be added to contract calls and FT/NFT transfers to ensure as
3232

3333
For instance, the following post-condition ensures that the principal initiating the transaction must send exactly 1000 uSTX, or else the transaction will abort.
3434

35-
```ts
35+
```ts -cn
3636
import { Pc } from '@stacks/transactions';
3737

3838
const postCondition = Pc.principal('STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6')
@@ -72,7 +72,7 @@ const postCondition = Pc.principal('STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6')
7272

7373
When creating a transaction, the mode of the transaction can be set to `Allow` or `Deny` to specify whether unspecified asset transfers are permitted.
7474

75-
```ts
75+
```ts -n
7676
import { PostConditionMode } from '@stacks/transactions';
7777

7878
const tx = await makeContractCall({
@@ -92,7 +92,7 @@ Essentially, the `postConditionMode` is what tells the Stacks node whether to re
9292

9393
Construct a post-condition for a certain amount of uSTX to be sent.
9494

95-
```ts
95+
```ts -cn
9696
import { Pc } from '@stacks/transactions';
9797

9898
const postCondition = Pc.principal('STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6')
@@ -104,7 +104,7 @@ const postCondition = Pc.principal('STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6')
104104

105105
Construct a post-condition for a certain amount of a specific FT to be sent.
106106

107-
```ts
107+
```ts -cn
108108
import { Pc } from '@stacks/transactions';
109109

110110
const postCondition = Pc.principal('STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6.token-ft')
@@ -116,7 +116,7 @@ const postCondition = Pc.principal('STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6.tok
116116

117117
Construct a post-condition for sending / not-sending a specific NFT.
118118

119-
```ts
119+
```ts -cn
120120
import { Pc } from '@stacks/transactions';
121121

122122
const postCondition = Pc.principal('STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6')
@@ -128,7 +128,7 @@ const postCondition = Pc.principal('STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6')
128128

129129
Construct a post-condition for sending / not-sending a specific SFT (Semi-fungible token).
130130

131-
```ts
131+
```ts -cn
132132
import { Cl, Pc } from '@stacks/transactions';
133133

134134
const postConditionForNFT = Pc.principal('STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6')

0 commit comments

Comments
 (0)