2. Add an `<intent-filter>` with the custom handler for Blockstack. Replace the host ("flamboyant-darwin-d11c17.netlify.app") with your own url once you have hosted your web app publicly.
2. Open the Project's `build.gradle` file.
3. Add the Jitpack repository `maven { url 'https://jitpack.io' }` to the `repositories` section.
3. Add one variable for the Blockstack sign-in flow and one for the Blockstack session that deals with all other function. This needs to be added before `onCreate`.
```kotlin
class MainActivity : AppCompatActivity() {
private var _blockstackSession: BlockstackSession? = null
private lateinit var blockstackSession: BlockstackSession
private lateinit var blockstackSignIn: BlockstackSignIn
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
@ -503,201 +425,180 @@ Now that you have created your initial project and verified it running in an emu
}
```
4. Replace the existing the `onCreate` function with the following:
```kotlin
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val scopes = arrayOf(Scope.StoreWrite)
val config = "https://flamboyant-darwin-d11c17.netlify.com"
.toBlockstackConfig(scopes)
4. Replace the existing the `onCreate` function with the following, use your own domain if you are already hosting your web app somewhere:
* Define the initial state for the `signInButton`.
* Supply authentication information for connecting to your Blockstack app: `appDomain` and `scopes` (for `redirectURI`, `manifestURI` the default values are used)
* Add a listener for the button click.
- Supply authentication information for connecting to your Blockstack app: `appDomain` (for `scopes`, `redirectURI`, `manifestURI` the default values are used)
- Add a listener for the button click.
- Handles the redirect intent from the sign-in flow.
Notice that the application in this example is a URI you have not set up.
Registering and application name takes time, so in time's interest you'll
use an existing app that is identical to the `hello-world` you created
earlier. For a production version, you'll need to replace `appDomain`,
`redirectURI`, `manifestURI` and `scopes` with values appropriate for your
app.
Notice that the application in this example is a URI you have not set up.
Registering and application name takes time, so in time's interest you'll
use an existing app (https://flamboyant-darwin-d11c17.netlify.app) that is identical to the `hello-world` you created
earlier. For a production version, you'll need to replace `appDomain`,
`redirectURI`, `manifestURI` and `scopes` with values appropriate for your
app.
5. Add a private function to reflect when a user successfully signs in.
```kotlin
private fun onSignIn(userData: UserData) {
userDataTextView.text = "Signed in as ${userData.decentralizedID}"
signInButton.isEnabled = false
}
```
```kotlin
private fun onSignIn(userData: UserData) {
userDataTextView.text = "Signed in as ${userData.decentralizedID}"
signInButton.isEnabled = false
}
```
6. Handle sign in requests with an `onNewIntent` function if the activity was already opened when signing in
6. Create a handler for the authentication response.
Retrieve the authentication token from the custom protocol handler call and
send it to the Blockstack session.
```kotlin
private fun handleAuthResponse(intent: Intent) {
val authResponse = intent.data?.getQueryParameter("authResponse")
if (authResponse != null) {
val userData = blockstackSession.handlePendingSignIn(authResponse)
if (userData.hasValue) {
// The user is now signed in!
runOnUiThread {
onSignIn(userData.value!!)
}
}
}
}
```
```kotlin
override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
7. Add `SignInProvider` interface for better user onboarding. Let the activity implement the interface and implement the member function `getBlockstackSignIn`
if (intent?.action == Intent.ACTION_VIEW) {
handleAuthResponse(intent)
}
}
```
```kotlin
class MainActivity : AppCompatActivity(), SignInProvider {
...
7. Create a handler for the authentication response.
By default, `getFile()` this method decrypts data; because the default `putFile()` encrypts it. In this case, the app shares statuses publicly. So, there is no need to decrypt.
5. Call `fetchData()` from the `componentDidMount()` method.
5. Call `fetchData()` from the by using React's `useEffect` method, which will fetch data whenever the component's username state is changed..
```javascript
// after setting up your component's state
componentDidMount() {
this.fetchData()
}
React.useEffect(() => {
fetchData();
}, [username]);
```
6. Save the file.
@ -578,8 +531,13 @@ process URL paths that contain the `.` (dot) character for example,
3. Add a single method to the `Profile` class that determines if the app is viewing the local user's profile or another user's profile.
Finally, you must conditionally render the logout button, status input textbox, and submit button so they don't show up when viewing another user's profile.
6. Replace the `render()` method with the following:
6. Replace the returned JSX in the `Profile` component with the following:
@ -189,19 +189,27 @@ in and sign out is handled in each of these files:
| `components/Signin.js ` | Code for the initial sign on page. |
| `components/Profile.js` | Application data storage and user sign out. |
The `src/components/App.js` code configures an `AppConfig` object and then uses this to create a `UserSession`. Then, the application calls a [`redirectToSignIn()`](https://blockstack.github.io/blockstack.js#redirectToSignIn) function which generates the `authRequest` and redirects the user to the Blockstack authenticator:
<!-- The `src/components/App.js` code configures an `AppConfig` object and then uses this to create a `UserSession`. Then, the application calls a [`redirectToSignIn()`](https://blockstack.github.io/blockstack.js#redirectToSignIn) function which generates the `authRequest` and redirects the user to the Blockstack authenticator: -->
```js
...
const userSession = new UserSession({ appConfig })
The `src/components/App.js` code configures a `UserSession` and other `authOptions`, which are passed to the `Connect` component. The `Connect` component acts as a "provider" for the rest of your application, and essentially creates a re-usable configuration for you.
export default class App extends Component {
In the `src/components/Signin.js` component, we are then calling the `useConnect` hook. This hook returns many helper functions, one of which is `doOpenAuth`. Calling this method will being the authentication process. First, it injects a modal into your application, which acts as a way of "warming up" your user to Blockstack authentication. When the user continues, they are redirected to the Blockstack authenticator, where they can finish signing up.
handleSignIn(e) {
e.preventDefault();
userSession.redirectToSignIn();
}
...
```js
import React from 'react';
import { useConnect } from '@blockstack/connect';
export const Signin = () => {
const { doOpenAuth } = useConnect();
return (
<button
onClick={() => doOpenAuth()}
>
Sign In with Blockstack
</button>
)
};
```
Once the user authenticates, the application handles the `authResponse` in the `src/components/Profile.js` file. :
description: Interacting with the Stacks 2.0 Blockchain
permalink: /:collection/:path.html
---
With the launch of Stacks 2.0, a new version of the Blockstack blockchain was released. There are two ways of interacting with the blockchain, either using the Stacks Blockchain API or by making RPC calls to a Stacks Core directly.
## Stacks Core API
The Stacks 2.0 blockchain's Rust implementation exposes RPC endpoints (in JSON format), which can be used to interface with the Stacks blockchain. [You can find the RPC API references here](https://docs.blockstack.org/core/smart/rpc-api.html).
## Stacks Blockchain API
The Stacks Blockchain API was built to maintain pageable materialized views of the Stacks 2.0 Blockchain. It is a server that exposes a RESTful JSON API, hosted by PBC. It introduces aidditonal functionality (e.g. get all transactions), as well as proxies calls directly to Stacks Node. [You can find the OpenAPI specification and documentation here](https://blockstack.github.io/stacks-blockchain-sidecar/).
*Note: Using this API requires you to trust the server, but provides a faster onboarding experience. It also addresses performance issues for which querying a node itself would be too slow or difficult.*
{% include note.html content="If you are looking for the Stacks 1.0 RPC endpoint references, please follow this <ahref='https://core.blockstack.org/'>link</a>." %}
@ -22,13 +22,14 @@ To install the Blockstack CLI, run the following command in terminal.
First, we are going to generate a new wallet for Testnet. To generate a wallet use the `make_keychain` command with the `-t` option for Testnet.
```
$ blockstack-cli make_keychain -t
$ blockstack make_keychain -t
{
"mnemonic": "private unhappy random runway boil scissors remove harvest fatigue inherit inquiry still before mountain pet tail mad accuse second milk client rebuild salt chase",
Using the `-H` option, we specify a connection to the testnet node at `http://neon.blockstack.org:20443`
By default, using the `-t` flag causes the CLI to connect to the neon testnet node at `http://neon.blockstack.org:20443`.
To specify a node to connect to, add the `-H` flag followed by the URL of the node `"http://localhost:20443"`. This flag can be used with all commands in this guide.
Verify that your account has tokens before continuing to the next step to send tokens.
Take note that the nonce for the account is `0`. We will be using this number in the next step.
## Sending Tokens
In order to send tokens, we will need the 5 parameters below.
@ -83,22 +88,21 @@ In order to send tokens, we will need the 5 parameters below.
Once we have the parameters, we can use the `send_tokens` command:
With this command we’re sending 1000 microstacks to the Stacks address `ST1WZ69T99RHQMQX3D91ZH2R37GV5NK8KDS5D5VDZ`.
With this command we’re sending 1000 microstacks to the Stacks address `ST2KMMVJAB00W5Z6XWTFPH6B13JE9RJ2DCSHYX0S7`.
We set the fee rate to `200` microstacks.
We set the fee rate to `200` microstacks. If you're not sure how much your transaction will cost. You can add the `-e` flag to estimate the transaction fee needed to get processed by the network, without broadcasting your transaction.
The nonce is set to `0` for this transaction, since it will be the first transaction we send from this account.
The nonce is set to `0` for this transaction, since it will be the first transaction we send from this account. For subsequent transactions, you will need to increment this number by `1` each time. You can check the current nonce for the account using the `balance` command.
Finally, the last parameter is the private key from earlier. `381314da39a45f43f45ffd33b5d8767d1a38db0da71fea50ed9508e048765cf301`
Once again, we’re using the `-t` option to indicate that this is a Testnet transaction, so it should be broadcasted to Testnet.
Using the `-T` option, we specify that we want to broadcast to the testnet node at `http://neon.blockstack.org:20443/v2/transactions`
If valid, your transaction will now be broadcasted to the network and you will see the transaction ID displayed on the screen.
To view the raw transaction without broadcasting, add the `-x` flag to your command.
"Neon" is phase 1 of the Stacks 2.0 testnet. In Neon, you can run a node and connect it to a public network. This guide will walk you through downloading and running your own node in the Neon network.
* TOC
{:toc}
### Prerequisites
Note: If you use Linux, you may need to manually install [`libssl-dev`](https://wiki.openssl.org/index.php/Libssl_API) and other packages. In your command line, run the following to get all packages:
### Download and install the `stacks-blockchain` repository
The first step is to ensure that you have Rust installed. If you are using macOS, Linux, or another Unix-like OS, run the following. If you are on a different OS, follow the [official Rust installation guide](https://www.rust-lang.org/tools/install).
```bash
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
```
If Rust is already installed, you might see this prompt. Select 'Proceed with Installation' to make sure you have the latest version installed.
![rustup prompt](/core/images/rust-install.png)
In case you just installed Rust, you will be prompted to run the following command to make the `cargo` command available:
You're all set to run a node that connects to the Neon network.
Back in the command line, run:
```bash
stacks-node neon
```
The first time you run this, you'll see some logs indicating that the Rust code is being compiled. Once that's done, you should see some logs that look something like the this:
```
INFO [1588108047.585] [src/chainstate/stacks/index/marf.rs:732] First-ever block 0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206
```
Awesome! Your node is now connected to the Neon network. Your node will receive new blocks when they are produced, and you can use your [node's RPC API](/core/smart/rpc-api) to send transactions, fetch information for contracts and accounts, and more.
### Creating an optimized binary
The steps above are great for trying to run a node temporarily. If you want to host a node on a server somewhere, you might want to generate an optimized binary. To do so, use the same configuration as above, but run:
```bash
cd testnet
cargo build --release --bin stacks-node
```
The above code will compile an optimized binary. To use it, run:
Clarity is a smart contracting language for use with the Stacks 2.0 blockchain. It supports programmatic control over digital assets.
Clarity is a programming language for writing smart contracts on the Stacks 2.0 blockchain. It supports programmatic control over digital assets.
* TOC
{:toc}
## Smart contracts
Smart contracts encode and enforce the rules for modifying a particular set of data as shared among people and entities who don't necessarily trust each other. For example, a smart contract could allow creators to add a new tv show to a streaming service, but require that users first pay for a decryption key before viewing it. To do this, the smart contract could be written such that the movie creator had to publicly disclose the decryption key in order to receive payment. The movie creators would therefore be incentivized to work on tv show episodes that people want to watch, based on the viewers' upfront payments that are locked-in until the creator releases the episode and the decryption key.
Smart contracts encode and enforce rules for modifying a particular set of data that is shared among people and entities who don't necessarily trust each other. For example, a smart contract can hold funds in escrow until multiple parties agree to release them, create its own ledger and keep track of its own novel tokens (fungible or non-fungible), and even help make supply chains more transparent.
Because smart contracts run on top of a blockchain, anyone can query them, and anyone can submit transactions to execute them. A smart contract execution can result in new transactions being written to the blockchain.
Because smart contracts are programs that exist in a blockchain, anyone can query them, and anyone can submit transactions to execute them. A smart contract execution can result in new transactions being written to the blockchain.
Apps use the blockchain to manage a global state that is visible to the public. To get back to the streaming service example, the global state could include a list of user that paid for a specific tv show episode. This is possible because the blockchain stores the history of all accepted transactions.
Anyone can audit the blockchain in order to independently verify that an app's global shared state has been managed correctly according to the smart contract's rules.
Apps can take advantage of smart contracts to manage a global state that is visible to the public. Anyone can audit the blockchain in order to independently verify that an app's global shared state has been managed correctly according to the smart contract's rules.
## Use cases
@ -44,12 +42,12 @@ A Clarity smart contract is composed of two parts — a data space and a set
Note some of the key Clarity language rules and limitations.
* The only atomic types are booleans, integers, fixed length buffers, and principals
* Recursion is illegal and there is no lambda function.
* The only primitive types are booleans, integers, buffers, and principals
* Recursion is illegal and there are no anonymous functions.
* Looping may only be performed via `map`, `filter`, or `fold`
* There is support for lists of the atomic types, however, the only variable length lists in the language appear as function inputs; There is no support for list operations like append or join.
* Variables are created via `let` binding and there is no support for mutating functions like `set`.
* There is support for lists, however, the only variable length lists in the language appear as function inputs; There is no support for list operations like append or join.
* Variables are immutable.
## Learning Clarity
You can try a [Hello World tutorial](tutorial.html) or jump right into the [language reference](clarityRef.html).
You can try a [Hello World tutorial](tutorial.html) or jump right into the [language reference](clarityRef.html).
The Stacks 2.0 testnet is currently in development. As part of the testnet, you can run a node and connect it to a public network. This guide will walk you through downloading and running your own node in the testnet network.
* TOC
{:toc}
### Prerequisites
Note: If you use Linux, you may need to manually install [`libssl-dev`](https://wiki.openssl.org/index.php/Libssl_API) and other packages. In your command line, run the following to get all packages:
Ensure that you have Rust installed. If you are using macOS, Linux, or another Unix-like OS, run the following. If you are on a different OS, follow the [official Rust installation guide](https://www.rust-lang.org/tools/install).
```bash
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
```
If Rust is already installed, you might see this prompt. Select 'Proceed with Installation' to make sure you have the latest version installed.
![rustup prompt](/core/images/rust-install.png)
In case you just installed Rust, you will be prompted to run the following command to make the `cargo` command available:
```bash
source $HOME/.cargo/env
```
### Download and install the `stacks-blockchain` repository
You're all set to run a node that connects to the testnet network.
Back in the command line, run:
```bash
stacks-node argon
```
The first time you run this, you'll see some logs indicating that the Rust code is being compiled. Once that's done, you should see some logs that look something like the this:
```
INFO [1588108047.585] [src/chainstate/stacks/index/marf.rs:732] First-ever block 0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206
```
Awesome! Your node is now connected to the testnet network. Your node will receive new blocks when they are produced, and you can use your [node's RPC API](/core/smart/rpc-api) to send transactions, fetch information for contracts and accounts, and more.
### Running a miner
Once you've followed the above steps to run a node, it's only a few more steps to run a proof-of-burn miner on the testnet.
First, we need to generate a keychain. With this keychain, we'll get some testnet BTC from a faucet, and then use that BTC to start mining.
To get a keychain, the simplest way is to use the `blockstack-cli`. We'll use the `make_keychain` command, and pass `-t` to indicate that we want a testnet keychain.
```bash
npx blockstack-cli@1.1.0-beta.1 make_keychain -t
```
After this runs, you'll probably see some installation logs, and at the end you should see some JSON that looks like this:
```json
{
"mnemonic": "exhaust spin topic distance hole december impulse gate century absent breeze ostrich armed clerk oak peace want scrap auction sniff cradle siren blur blur",
We need to get some testnet BTC to that address. Grab the `btcAddress` field, and head over to [the Stacks testnet website](https://testnet.blockstack.org/faucet). In the BTC faucet section, past in your `btcAddress`, and submit. You'll be sent 0.5 testnet BTC to that address. **Don't lose this information** - we'll need to use the `privateKey` field later on.
Now, we need to configure out node to use this Bitcoin keychain. In the `stacks-blockchain` folder, create a new file called `testnet/stacks-node/conf/testnet-miner-conf.toml`.
Now, grab your `privateKey` from earlier, when you ran the `make_keychain` command. Replace the `seed` field with your private key. Save and close this configuration file.
Your node should start. It will take some time to sync, and then your miner will be running!
### Creating an optimized binary
The steps above are great for trying to run a node temporarily. If you want to host a node on a server somewhere, you might want to generate an optimized binary. To do so, use the same configuration as above, but run:
```bash
cd testnet/stacks-node
cargo build --release --bin stacks-node
```
The above code will compile an optimized binary. To use it, run:
@ -37,7 +37,6 @@ You have to select a template and a name for your local folder. For the counter
```bash
? Template - one of [hello-world, counter]: counter
? Project name: (clarity-counter)
```
Finally, the project dependencies are installed and your project is ready for development. Because you already completed the [Hello World tutorial](tutorial.html), the project structure is familiar to you. The main difference is that we have additional tests for a new counter smart contract.
@ -65,6 +64,10 @@ counter contract test suite
1 passing (734ms)
3 failing
... # error details
npm ERR! Test failed. See above for more details.
```
It looks like we see some failed tests! That is on purpose - we will implement the new smart contract in the next steps! After every step in this tutorial, we will rerun the tests to ensure we're on the right track.
@ -89,7 +92,7 @@ Let's get familiar with the tests to understand what the new smart contract shou
The file was already created during the project setup.
2. With the editor of your choice, open the file and add the following lines of code:
2. With the editor of your choice, open `contracts/counter.clar` and add the following lines of code:
```cl
(define-data-var counter int 0)
@ -151,16 +154,19 @@ Let's get familiar with the tests to understand what the new smart contract shou
Connect is built to use popups with the [`window.postMessage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage) API, which provides a much better and seamless user experience. However, there are times when this flow can fail. For example, the popup may be blocked, or the `window.postMessage` API might not work properly (which often happens on mobile browsers).
To make sure your app handles this gracefully, you'll need to handle the case where authentication is performed through regular HTTP redirects. With redirects, your users will be sent back to your app at a URL like:
`${authOptions.redirectTo}?authResponse=....`
To finalize authentication with this flow, you'll need to utilize the `UserSession` methods `isSignInPending()` and `handlePendingSignIn()`. For more information, check out the [blockstack.js API reference](https://blockstack.github.io/blockstack.js/).
Blockstack is valuable to users, but it can also be a barrier to those unfamiliar with Blockstack. The following guidelines serve to remedy that and help you onboard as many new users as you can.
### Delay Blockstack onboarding as long as possible
People will often leave apps when things are asked of them before they experience the app. Give them a chance to try your app before you ask them to sign up with Blockstack. For example, a note taking app could let a new user write a couple of notes before prompting them to save their progress.
### Provide an easy way in for new users
Many new users to your app will not be familiar with Blockstack yet and will be hesitant to click a Blockstack-branded button. Provide a generic button for users that are new to your app and Blockstack. Blockstack Connect will introduce new users to Blockstack and recognize existing users.
### Provide a quick way for existing users to sign in
You can point users to a specific part of the Blockstack App. For instance, a “Sign in” button on your website can redirect users to the sign in flow of the Blockstack App. If you do this, make sure you also have an option that is explicitly for new users and that points to the sign up flow.
To implement this functionality, check out our section on sending users to sign in immediately.
With Connect, you can interact with the Stacks 2.0 blockchain. You can allow your users to send transactions and interact with smart contracts.
* TOC
{:toc}
## How it works
For your app's users to be able to execute a smart contract function, they need to sign and broadcast a transaction. It's important that users remain control of the private keys that sign these transactions. Connect provides an easy-to-use workflow that allows your users to securely sign transactions.
Connect allows you to open the authenticator with parameters indicating the details of the transaction - like the smart contract address, function name, and specific arguments. Your users get the chance to see these details, and then sign and broadcast the transaction in a single click. Their transaction will be securely signed and broadcasted onto the Stacks blockchain. After this is done, a callback is fired to allow you to update your app.
## Usage
<divclass="uk-card uk-card-default uk-card-body">
<h5class="uk-card-title">Transaction signing is still in progress</h5>
<p>
To use these features, make sure you install the <code>testnet</code> tag the <code>@blockstack/connect</code> NPM package. You can do this by running <code>npm install --save @blockstack/connect@testnet</code>, or by specifying <code>testnet</code> as the version in
your package.json file.
</p>
<p>
The Stacks 2.0 blockchain is still in testnet, and our web app integration is also still in beta. In order to use transaction signing in your application, you need to use the configuration `authOrigin` with `@blockstack/connect`.
</p>
@ -33,34 +26,81 @@ Connect allows you to open the authenticator with parameters indicating the deta
</pre>
</div>
### `ContractCallOptions`
* TOC
{:toc}
## How it works
For your app's users to be able to execute a smart contract function, they need to sign and broadcast a transaction. It's important that users remain in control of the private keys that sign these transactions. Connect provides an easy-to-use workflow that allows your users to securely sign transactions.
Connect allows you to open the authenticator with parameters indicating the details of the transaction - like the smart contract address, function name, and specific arguments. Your users get the chance to see these details, and then sign and broadcast the transaction in a single click. Their transaction will be securely signed and broadcasted onto the Stacks blockchain. After this is done, a callback is fired to allow you to update your app.
## Calling Clarity Contract Functions
Once you have a Clarity smart contract built and deployed, you'll naturally want to allow your app's users to interact with it.
When signing a transaction, you need to specify a few details. Here is the exact interface that describes what options you have:
To initiate a contract call transaction, use the `openContractCall` function.
```ts
export interface ContractCallOptions {
import { openContractCall } from '@blockstack/connect';
When calling `openContractCall`, you need to specify a few details. Here is the exact interface that describes what options you have:
```ts
interface ContractCallOptions {
contractAddress: string;
functionName: string;
contractName: string;
functionArgs?: any[];
authOrigin?: string;
userSession?: UserSession;
appDetails?: AuthOptions['appDetails'];
finished?: (data: FinishedTxData) => void;
appDetails: {
name: string;
icon: string;
};
finished: (data: FinishedTxData) => void;
}
```
parameter | type | default | optional | description
---|---|---|---|---
contractAddress | string | | false | The Stacks address that published this contract
contractName | string | | false | The name that was used when publishing this contract
functionName | string | | false | The name of the function you're calling. This needs to be a [public function](/core/smart/clarityRef.html#define-public).
functionArgs | array | | false | The arguments you're calling the function with. You'll need to provide the Clarity type with each argument. See the below section for details.
userSession | UserSession | | true | A `UserSession` instance
appDetails | object | | false | A dictionary that includes `name` and `icon`
finished | function | | false | A callback that is fired when the transaction is signed and broadcasted. Your callback will receive an object back with a `txId` and a `txRaw`, both of which are strings.
parameter | type | optional | description
---|---|---|---
contractAddress | string | false | The Stacks address that published this contract
contractName | string | false | The name that was used when publishing this contract
functionName | string | false | The name of the function you're calling. This needs to be a [public function](/core/smart/clarityRef.html#define-public).
functionArgs | array | false | The arguments you're calling the function with. You'll need to provide the Clarity type with each argument. See the below section for details. Defaults to `[]`.
appDetails | object | false | A dictionary that includes `name` and `icon`
finished | function | false | A callback that is fired when the transaction is signed and broadcasted. Your callback will receive an object back with a `txId` and a `txRaw`, both of which are strings.
authOrigin | string | true | The location of the authenticator. This is only necessary when developing the authenticator locally, or when using beta features. Defaults to `"https://app.blockstack.org"`.
#### Passing Clarity types with function arguments
### Passing Clarity types with function arguments
To be able to serialize your transaction properly, you need to provide the appropriate Clarity type with each argument. These types are named the same as they are in Clarity. The `value` that you pass must be a string. The types you can pass are:
@ -68,7 +108,7 @@ To be able to serialize your transaction properly, you need to provide the appro
- `int` - i.e. `"12"`
- `bool` - can be "true", "false", "0" or "1"
- `buff` - i.e. `"asdf"`
- `principal` - This can be a contract principal, or a standard principal. Examples: `"ST22T6ZS7HVWEMZHHFK77H4GTNDTWNPQAX8WZAKHJ"` or `"ST22T6ZS7HVWEMZHHFK77H4GTNDTWNPQAX8WZAKHJ.my-contract"`.
- `principal` - This can be a contract principal, or a standard principal. [Read more about principals](/core/smart/principals.html). Examples: `"ST22T6ZS7HVWEMZHHFK77H4GTNDTWNPQAX8WZAKHJ"` or `"ST22T6ZS7HVWEMZHHFK77H4GTNDTWNPQAX8WZAKHJ.my-contract"`.
Using these types, each argument is an object with the keys `type` and `value`. For example:
@ -87,40 +127,110 @@ const functionArguments = [
If you're using Typescript, these Clarity types can be imported as `ContractCallArgumentType` from `@blockstack/connect`.
### Usage in ES6 (non-React) apps
## Stacks (STX) Token Transfers
STX token transfers can be initiated with the `openSTXTransfer` function.
```ts
import { openContractCall } from '@blockstack/connect';
import { openSTXTransfer } from '@blockstack/connect';
When calling `openSTXTransfer`, you need to specify a few details. Here are the options you have:
```ts
interface STXTransferOptions {
recipient: string;
amount: string;
memo?: string;
authOrigin?: string;
appDetails: {
name: string;
icon: string;
};
finished: (data: FinishedTxData) => void;
}
```
### Usage in React Apps
parameter | type | optional | description
---|---|---|---
recipient | string | false | The STX Address for the recipient of this STX transfer
amount | string | false | The amount of microstacks (µSTX) to be transferred. This argument is a string to prevent floating point errors. There are 1,000,000 µSTX per STX.
memo | string | true | An optional memo to include in the transaction.
appDetails | object | false | A dictionary that includes `name` and `icon`
finished | function | false | A callback that is fired when the transaction is signed and broadcasted. Your callback will receive an object back with a `txId` and a `txRaw`, both of which are strings.
authOrigin | string | true | The location of the authenticator. This is only necessary when developing the authenticator locally, or when using beta features. Defaults to `"https://app.blockstack.org"`.
## Deploying Clarity Contracts
To allow your app's users to deploy arbitrary Clarity contracts, use the `openContractDeploy` method.
```ts
import { openContractDeploy } from '@blockstack/connect';
Here is the interface for the options you can provide to `openContractDeploy`:
```ts
interface ContractDeployOptions {
codeBody: string;
contractName: string;
authOrigin?: string;
appDetails: {
name: string;
icon: string;
};
finished: (data: FinishedTxData) => void;
}
```
parameter | type | optional | description
---|---|---|---
codeBody | string | false | The Clarity source code for this contract
contractName | string | false | The name for this contract
appDetails | object | false | A dictionary that includes `name` and `icon`
finished | function | false | A callback that is fired when the transaction is signed and broadcasted. Your callback will receive an object back with a `txId` and a `txRaw`, both of which are strings.
authOrigin | string | true | The location of the authenticator. This is only necessary when developing the authenticator locally, or when using beta features. Defaults to `"https://app.blockstack.org"`.
## Usage in React Apps
Make sure you follow the [setup instructions](/develop/connect/get-started.html#in-react-apps) first. When you're using `useConnect`, you don't have to specify `appDetails` - we'll pick that up from your existing configuration.
Each transaction signing method is exposed through the `useConnect` hook, but they're prefixed with `do` instead of `open`, to remain consistent with our React action naming standards.
@ -29,7 +29,7 @@ Radiks consists of a database, a pre-built server, and a client. A developer add
2. Saves a raw JSON of this encrypted data in the user's Gaia storage.
3. Stores the encrypted data on the Radiks server.
Radiks can store both public and sensitive, non-public data since all data is encrypted by default before it leaves the client. Your application can query Radiks for public data and then decrypt the sensitive information on the client. Radix servers can only return queries for unencrypted data.
Radiks can store both public and sensitive, non-public data since all data is encrypted by default before it leaves the client. Your application can query Radiks for public data and then decrypt the sensitive information on the client. Radiks servers can only return queries for unencrypted data.
@ -4,9 +4,9 @@ A decentralized application (DApp) and the Blockstack Browser communicate during
![](/storage/images/app-sign-in.png)
When a user chooses to **Sign in with Blockstack** on a DApp, it calls the `redirectToSignIn()` method which sends an `authRequest` to the Blockstack Browser. Blockstack passes the token in via a URL query string in the `authRequest` parameter:
When a user chooses to **Sign in with Blockstack** on a DApp, it calls the `doOpenAuth()` method which sends an `authRequest` to the Blockstack Authenticator. Blockstack passes the token in via a URL query string in the `authRequest` parameter:
When the Blockstack Browser receives the request, it generates an (`authResponse`) token to the application using an _ephemeral transit key_ . The ephemeral transit key is just used for the particular instance of the application, in this case, to sign the `authRequest`. The application stores the ephemeral transit key during the request generation. The public portion of the transit key is passed in the `authRequest` token. The Blockstack Browser uses the public portion of the key to encrypt an _app-private key_ which is returned via the `authResponse`.