title
stringlengths 22
74
| content
stringlengths 0
10.1k
| url
stringlengths 37
188
| code_snippets
sequencelengths 1
8
⌀ |
---|---|---|---|
Introduction | Actions & Alerts | Introduction
Actions
Actions and Blinks are an ambitious new protocol in collaboration with Solana—& a developer stack by Dialect—to share Solana transactions everywhere.
Actions are a protocol for creating & delivering Solana transactions through URLs, making Solana sharable everywhere. Blinks, or Blockchain Links, are clients that detect Action URLs & unfurl them into full experiences.
Blinks are like Link Previews with interactive capabilities.
We've teamed up with Solana's leading wallets to bring Actions and Blinks right to Twitter, with native support in Phantom, Backpack, and soon in Solflare. You can try them out today by enabling Blinks from your favorite wallet: ⚙️ → Enable Actions/Blinks.
Or try Dialect's dedicated Blinks Chrome extension.
Solana's top teams are building with Actions today.
These docs describe the Actions Specification, how Blinks work to unfurl Actions APIs, and provide practical resources on how to get started developing today.
Alerts
Dialect powers alerts for many of Solana's most loved projects. All of our tooling is open source and free to use. Get started and send your first test alert in under 15 minutes.
See the Getting started section for more information.
Next
Actions
Last updated 1 month ago | https://docs.dialect.to/documentation | null |
Actions | Actions & Alerts | Actions
Actions are APIs that deliver signable transactions, and soon signable messages.
Blockchain links, or Blinks, are clients that determine if URLs conform to the Actions spec, & introspect the underlying Actions APIs to construct interfaces for them.
Any client that fully introspects an Actions API to build a complete interface for it is a Blink. Therefore, not all clients that consume Actions APIs are Blinks.
Actions are hosted at URLs, and are therefore sharable by their URL.
Actions are comprised of URL scheme, a GET route, and a POST route to the Action Provider:
A URL scheme for identifying Actions Providers
A GET request and response, to and from, an action URL, for presenting the client with human-readable information.
A POST request and response, to and from an action URL, for constructing transactions (and soon messages) for signing and submission to the blockchain.
This documentation covers:
the Actions specification,
how the specification relates to blinks, as well as
more practical guides on how to build actions and
how to build blinks clients, whether natively into a web or mobile dapp, or via a Chrome extension for delivery on 3rd party sites like Twitter, and
materials on Security and the Public Registry.
Let's get started.
Previous
Introduction
Next
Quick Start
Last updated 10 days ago | https://docs.dialect.to/documentation/actions | null |
Quick Start | Actions & Alerts | These docs cover the Actions and Blinks specifications and how they work. For a more practical guide on creating your first action, testing and deploying it, and getting it ready to use on Twitter, see the Guide below.
If you're interested in building a Blinks client, see the Guide on building Blinks.
Last updated 24 days ago
Was this helpful? | https://docs.dialect.to/documentation/actions/quick-start | null |
Specification | Actions & Alerts | Specification
This section of the docs describes the Actions Specification, including aspects of the specification that concern Blinks. Namely, it covers
URL Schemes
GET & POST schemas and capabilities
OPTIONS request and CORS handling
Execution and lifecycle
Multi-actions and action input types
The role of actions.json in upgrading website URLs with Blinks capabilities
Aspects of Blinks that are concerned with the Actions specification.
For more practical guides, see Actions and Blinks.
Previous
Quick Start
Next
URL Scheme
Last updated 9 days ago | https://docs.dialect.to/documentation/actions/specification | null |
URL Scheme | Actions & Alerts | URL Scheme
Solana Actions conform to a URL scheme denoted by solana-action:. They are a set of standard, interactive HTTP requests for constructing transactions or messages for the client to sign with a wallet keypair.
Copy
solana-action:<link>
The link field must be a conditionally URL-encoded absolute HTTPS URL.
The URL may contain URL-encoded query parameters, which will prevent conflicts with any potential Actions protocol parameters added via the protocol specification.
The URL does not need to be URL-encoded if it does not contain any query parameters.
Clients are responsible for decoding the URL, and if unsuccessful, should reject the action as malformed.
Previous
Specification
Next
GET
Last updated 1 month ago | https://docs.dialect.to/documentation/actions/specification/url-scheme | [
"solana-action:<link>"
] |
POST | Actions & Alerts | POST
POST Request
Actions support HTTP POST JSON requests to their URL with the the body payload:
Copy
{
"account": "<account>"
}
where account is a base58-encoded representation of the public key of the user making the request.
Clients should use Accept-Encoding headers and the Action service should respond with a Content-Encoding header for HTTP compression.
Post Response
Actions services should respond to POST requests with an HTTP OK JSON response with a payload of the format below.
Copy
export interface ActionPostResponse {
/** base64-encoded transaction */
transaction: string;
/** optional message, can be used to e.g. describe the nature of the transaction */
message?: string;
}
The client must handle HTTP client errors, server errors, and redirect responses.
The endpoint should respond with a Content-Type header of application/json.
Action Chaining [Upcoming]
The following specification is not supported by Dialect's Blinks Client. We're working on bringing Client support as soon as possible.
In the next few weeks, the Dialect Blinks Client will be rolling out support for Action Chaining, which allows the confirmation of an action on-chain to present the context of a new action to the user, constructing what is essentially a 'chain' of actions in a successive series.
The changes to the specification to enable action chaining are:
Copy
export interface ActionPostResponse<T extends ActionType = ActionType> {
/** base64 encoded serialized transaction */
transaction: string;
/** describes the nature of the transaction */
message?: string;
links?: {
/**
* The next action in a successive chain of actions to be obtained after
* the previous was successful.
*/
next: NextActionLink;
};
}
export type NextActionLink = PostNextActionLink | InlineNextActionLink;
/** @see {NextActionPostRequest} */
export interface PostNextActionLink {
/** Indicates the type of the link. */
type: "post";
/** Relative or same origin URL to which the POST request should be made. */
href: string;
}
/**
* Represents an inline next action embedded within the current context.
*/
export interface InlineNextActionLink {
/** Indicates the type of the link. */
type: "inline";
/** The next action to be performed */
action: NextAction;
}
To chain multiple actions together, in any ActionPostResponse include a links.next of either
PostNextActionLink - POST request link with a same origin callback url to receive the signature and user's account in the body. This callback url should respond with a NextAction.
InlineNextActionLink - Inline metadata for the next action to be presented to the user immediately after the transaction has confirmed. No callback will be made.
After the ActionPostResponse included transaction is signed by the user and confirmed on-chain, the blink client should either:
execute the callback request to fetch and display the NextAction, or
if a NextAction is already provided via links.next, the blink client should update the displayed metadata and make no callback request
If the callback url is not the same origin as the initial POST request, no callback request should be made. Blink clients should display an error notifying the user.
Copy
/** The next action to be performed */
export type NextAction = Action<"action"> | CompletedAction;
/** The completed action, used to declare the "completed" state within action chaining. */
export type CompletedAction = Omit<Action<"completed">, "links">;
Based on the type, the next action should be presented to the user via blink clients in one of the following ways:
action - (default) A standard action that will allow the user to see the included Action metadata, interact with the provided LinkedActions, and continue to chain any following actions.
completed - The terminal state of an action chain that can update the blink UI with the included Action metadata, but will not allow the user to execute further actions.
If no links.next is not provided, blink clients should assume the current action is final action in the chain, presenting their "completed" UI state after the transaction is confirmed.
Previous
GET
Next
OPTIONS & CORS
Last updated 1 day ago | https://docs.dialect.to/documentation/actions/specification/post | [
"{account: <account>}",
"export interface ActionPostResponse {/** base64-encoded transaction */transaction: string;/** optional message, can be used to e.g. describe the nature of the transaction */message?: string;}",
"export interface ActionPostResponse<T extends ActionType = ActionType> {transaction: string;message?: string;links?: {next: NextActionLink;};}export type NextActionLink = PostNextActionLink | InlineNextActionLink;export interface PostNextActionLink {type: post;href: string;}export interface InlineNextActionLink {type: inline;action: NextAction;}"
] |
OPTIONS & CORS | Actions & Alerts | OPTIONS & CORS
To enable Cross-Origin Resource Sharing (CORS) for Actions clients (including blinks), all Action endpoints must handle HTTP OPTIONS requests with appropriate headers. This ensures clients can successfully pass CORS checks for all subsequent requests from the same origin domain.
An Actions client may perform 'preflight' requests to the Action URL endpoint in the form of an OPTIONS HTTP method to check if the GET request will pass all CORS checks. The OPTIONS method should respond with all the required HTTP headers to allow clients (like blinks) to properly make all the subsequent requests from the origin domain.
The minimum required HTTP headers are:
Access-Control-Allow-Origin with a value of *
Access-Control-Allow-Methods with a value of GET,POST,PUT,OPTIONS
Access-Control-Allow-Headers with a minimum value of Content-Type, Authorization, Content-Encoding, Accept-Encoding
CORS Headers for Actions.json
The actions.json file response must also return valid CORS headers for GET and OPTIONS requests as noted in the actions.json section of these docs
Previous
POST
Next
Execution & Lifecycle
Last updated 11 days ago | https://docs.dialect.to/documentation/actions/specification/options-and-cors | null |
GET | Actions & Alerts | GET
Request
Action clients first make an HTTP GET JSON request to the Action URL. The request should be made with an Accept-Encoding header.
Response
The Action URL should respond with an HTTP OK JSON response with the body payload below, or with an HTTP error.
The client must handle HTTP client errors, server errors, and redirect responses.
The endpoint should respond with a Content-Encoding header for HTTP compression.
The client should not cache the response except as instructed by HTTP caching response headers.
The client should then display the response body information, like icon, title, description, and labels.
GET Response Body
A successful GET response with status HTTP OK should conform to the following payload:
Copy
export interface ActionGetResponse {
/** url of some descriptive image for the action */
icon: string;
/** title of the action */
title: string;
/** brief description of the action */
description: string;
/** text to be rendered on the action button */
label: string;
/** optional state for disabling the action button(s) */
disabled?: boolean;
/** optional list of related Actions */
links?: {
actions: LinkedAction[];
};
/** optional (non-fatal) error message */
error?: ActionError;
}
icon - Must be an absolute HTTP or HTTPS URL of an image describing the action. Supported image formats are SVG, PNG, or WebP image. If none of the above, the client ust reject it as malformed.
title - A UTF-8 string for the title of the action.
description - A UTF-8 string providing a brief description of the action.
label - AUTF-8 string to be displayed on the button used to execute the action. Labels should not exceed 5 word phrases and should start with a verb, to emphasize the action to be taken. For example, "Mint NFT", "Vote Yes", or "Stake 1 SOL".
disabled - An optional boolean value. If present, all buttons associated with the action should be disabled. This optional value is falsey, in that its absence is equivalent to enabled=true. Examples of disabled in use could include an NFT collection that has minted out, or a governance proposal whose voting period as ended.
error - An optional error indication for non-fatal errors, intended to be human readable and presented to the end-user. If set, it should not prevent the client from interpreting the action or displaying it to the user. For example, the error can be used together with disabled to display a reason like business constraints, authorization, the state, or an error of external resource.
Copy
export interface ActionError {
/** non-fatal error message to be displayed to the user */
message: string;
}
links.actions - An optional array of addtional actions related to this action. Each linked action is given only a label, to be rendered on a button, and an associated Action URL at href. No additional icons, titles, or descriptions are provided. For example, a governance vote action endpoint may return three options for the user: "Vote Yes", "Vote No", and "Abstain from Vote".
If no links.actions is provided, the client should render a single button using the root label string and make the POST request to the same action URL endpoint as the initial GET request.
If any links.actions are provided, the client should only render buttons and input fields based on the items listed in the links.actions field. The client should not render a button for the contents of the root label.
Copy
export interface LinkedAction {
/** URL endpoint for an action */
href: string;
/** button text rendered to the user */
label: string;
/**
* Parameters to accept user input within an action
* @see {ActionParameter}
* @see {ActionParameterSelectable}
*/
parameters?: Array<TypedActionParameter>;
}
/** Parameter to accept user input within an action */
export interface ActionParameter {
/** input field type */
type?: ActionParameterType;
/** parameter name in url */
name: string;
/** placeholder text for the user input field */
label?: string;
/** declare if this field is required (defaults to `false`) */
required?: boolean;
/** regular expression pattern to validate user input client side */
pattern?: string;
/** human-readable description of the `type` and/or `pattern`, represents a caption and error, if value doesn't match */
patternDescription?: string;
/** the minimum value allowed based on the `type` */
min?: string | number;
/** the maximum value allowed based on the `type` */
max?: string | number;
}
Note that the complete ActionParameter interface is not supported by Blinks clients, and we're working on bringing client support as soon as possible. As of now, the fields in ActionParameter that are supported are name, label and required. ActionParameterSelectable is not currently supported as well.
Note that ActionParameter represents a second action type, one with a multiple input types, as well as an extended version of ActionParameter called ActionParameterSelectable which are expanded on in Action Types.
For more information on how actions are linked to create multi-action experiences, see Multi-Actions.
Examples
Example GET Response
The following example response provides a single "root" action that is expected to be presented to the user a single button with a label of "Buy WIF":
Copy
{
"title": "Buy WIF with SOL",
"icon": "<url-to-image>",
"description": "Buy WIF using SOL. Choose a USD amount of SOL from the options below.",
"label": "Buy WIF" // button text
}
The following example response provides 3 related action links that allow the user to click one of 3 buttons to buy WIF:
Copy
{
"title": "Buy WIF with SOL",
"icon": "<url-to-image>",
"description": "Buy WIF using SOL. Choose a USD amount of SOL from the options below.",
"label": "Buy WIF",
"links": {
"actions": [
{
"label": "$10", // button text
"href": "/api/buy?amount=10"
},
{
"label": "$100", // button text
"href": "/api/buy?amount=100"
},
{
"label": "$1,000", // button text
"href": "/api/buy?amount=1000"
}
]
}
}
Example GET Response with Parameters
The following examples response demonstrate how to accept text input from the user (via parameters) and include that input in the final POST request endpoint (via the href field within a LinkedAction):
The following example response provides the user with 3 linked actions to buy WIF: a button labeled "$10", another button labeled "$100", a third button labeled "$1,000" and a text input field that allows the user to enter a specific "amount" value that will be sent to the Action API:
Copy
{
"title": "Buy WIF with SOL",
"icon": "<url-to-image>",
"description": "Buy WIF using SOL. Choose a USD amount of SOL from the options below, or enter a custom amount.",
"label": "Buy WIF", // not displayed since `links.actions` are provided
"links": {
"actions": [
{
"label": "$10", // button text
"href": "/api/buy?amount=10"
// no `parameters` therefore not a text input field
},
{
"label": "$100", // button text
"href": "/api/buy?amount=100"
// no `parameters` therefore not a text input field
},
{
"label": "$1,000", // button text
"href": "/api/buy?amount=1000"
// no `parameters` therefore not a text input field
},
{
"label": "Buy WIF", // button text
"href": "/api/buy?amount={amount}",
"parameters": [
{
"name": "amount", // field name
"label": "Enter a custom USD amount" // text input placeholder
}
]
}
]
}
}
The following example response provides a single input field for the user to enter an amount which is sent with the POST request (either as a query parameter or a subpath can be used):
Copy
{
"icon": "<url-to-image>",
"label": "Buy WIF",
"title": "Buy WIF with SOL",
"description": "Buy WIF using SOL. Choose a USD amount of SOL from the options below, or enter a custom amount.",
"links": {
"actions": [
{
"label": "Buy WIF", // button text
"href": "/api/buy/{amount}", // or /api/buy?amount={amount}
"parameters": [
// {amount} input field
{
"name": "amount", // input field name
"label": "Enter a custom USD amount" // text input placeholder
}
]
}
]
}
}
Note that the aspect ratio of the url-to-image is generally flexible and the only limitation is that the max height of the image must be equal to the max width of the blink container. The recommended size for 1:1 aspect ratio is 440px x 440px
Previous
URL Scheme
Next
POST
Last updated 13 hours ago | https://docs.dialect.to/documentation/actions/specification/get | [
"{title: Buy WIF with SOLicon: <url-to-image>description: Buy WIF using SOL. Choose a USD amount of SOL from the options below.label: Buy WIF}",
"{title: Buy WIF with SOLicon: <url-to-image>,description: Buy WIF using SOL. Choose a USD amount of SOL from the options below.,label: Buy WIF,links: {actions: [{label: $10, href: /api/buy?amount=10},{label: $100,href: /api/buy?amount=100},{label: $1,000, href: /api/buy?amount=1000}]}}",
"{title: Buy WIF with SOL,icon: <url-to-image>,description: Buy WIF using SOL. Choose a USD amount of SOL from the options below, or enter a custom amount.,label: Buy WIF,links: {actions: [{label: $10,href: /api/buy?amount=10},{label: $100,href: /api/buy?amount=100},{label: $1,000,href: /api/buy?amount=1000},{label: Buy WIF, href: /api/buy?amount={amount},parameters: [{name: amount,label: Enter a custom USD amount}]}]}}",
"{icon: <url-to-image>,label: Buy WIF,title: Buy WIF with SOL,description: Buy WIF using SOL. Choose a USD amount of SOL from the options below, or enter a custom amount.,links: {actions: [{label: Buy WIF,href: /api/buy/{amount},parameters: [{name: amount,label: Enter a custom USD amount}]}]}}",
"export interface ActionGetResponse {icon: string;title: string;description: string;label: string;disabled?: boolean;links?: {actions: LinkedAction[];};error?: ActionError;}",
"export interface ActionError {message: string;}",
"export interface LinkedAction {href: string;label: string;parameters?: Array<TypedActionParameter>;}export interface ActionParameter {type?: ActionParameterType;name: string;label?: string;required?: boolean;pattern?: string;patternDescription?: string;min?: string | number;max?: string | number;}"
] |
Execution & Lifecycle | Actions & Alerts | Execution & Lifecycle
We've describe the URL scheme, as well as the GET and POST APIs. Let's now describe the full Action execution flow, which follows a typical HTTP REST API lifecycle:
The client makes a GET request to the Action URL.
The Action API returns a GET response body of human-readable metadata describing the actions at this URL, according to the specification above.
The end-user chooses an action to take from the options available, and the client makes a POST request to the server at the specified URL, either the same as the GET URL, or different.
The Action Provider receives this request, constructs a transaction (or soon message) that constitutes the action to be taken by the end-user, and returns a POST response body containing this transaction.
The client takes this transaction and prepares it for the end-user to sign by sending it to a client-side wallet such as a chrome extension or embedded wallet.
The user signs the transaction (or soon message), and the client handles submission of this transaction to the blockchain.
Validation
Actions providers support validation. GET and POST requests may first validate whether the action is able to be taken, and may customize their response metadata, and use disabled if validation fails.
For example, GET requests for a NFT that is up for auction may return an error message “This auction has completed” and render the “Bid” button as disabled . Or a GET request for a vote for a DAO governance proposal whose voting window has closed may return the error message “This proposal is no longer up for a vote” and the Vote yes & Vote no buttons as “disabled”.
Execution
Once signed, transactions are submitted to the blockchain, and the client is responsible for tracking the execution lifecycle.
Persistence
Actions do not persist their execution state beyond a single session. If a user refreshes the client, or leaves and comes back at a later time, past or current interactions with the Action are no longer reflected by the client.
Previous
OPTIONS & CORS
Next
Multi-Actions
Last updated 1 month ago | https://docs.dialect.to/documentation/actions/specification/execution-and-lifecycle | null |
Multi-Actions | Actions & Alerts | Multi-Actions
To support multiple actions, Action Provider GET responses may include additional action URLs via the links attribute.
Copy
export interface LinkedAction {
/** URL endpoint for an action */
href: string;
/** button text rendered to the user */
label: string;
/** Parameter to accept user input within an action */
parameters?: [ActionParameter];
}
/** Parameter to accept user input within an action */
export interface ActionParameter {
/** parameter name in url */
name: string;
/** placeholder text for the user input field */
label?: string;
/** declare if this field is required (defaults to `false`) */
required?: boolean;
}
All of these linked actions are themselves Action URLs at href, and may themselves also return multiple actions.
Linked actions, although valid actions, only provide a label and href as they are are intended to be used to display additional buttons in a single Blink.
Such examples include “Buy 1 SOL”, “Buy 5 SOL”, “Buy 10 SOL” as options within a single API call or single interface.
Linked actions hrefs support both absolute and relative paths.
The optional parameters attribute allows for a second action type, which is covered in the next section.
NOTE: If you're looking to create blinks with multiple-input forms like the one below, check out the next section.
Sample Multi-Input Form Blink
Previous
Execution & Lifecycle
Next
Action Types
Last updated 25 days ago | https://docs.dialect.to/documentation/actions/specification/multi-actions | [
"export interface LinkedAction {href: string;label: string;parameters?: [ActionParameter];}export interface ActionParameter {name: string;label?: string;required?: boolean;}"
] |
actions.json | Actions & Alerts | https://docs.dialect.to/documentation/actions/specification/actions.json | null |
|
Action Types | Actions & Alerts | Action Types
Linked Actions support both fixed as well as parameterized values, as specified by the optional parameters attribute.
Parameterized actions signal to the client that users may provide a variable input for the action.
Apart from simple text input fields, ActionParameter now also accepts other input types as specified in ActionParameterType.
Copy
export interface LinkedAction {
/** URL endpoint for an action */
href: string;
/** button text rendered to the user */
label: string;
/**
* Parameters to accept user input within an action
* @see {ActionParameter}
* @see {ActionParameterSelectable}
*/
parameters?: Array<TypedActionParameter>;
}
/** Parameter to accept user input within an action */
export interface ActionParameter {
/** input field type */
type?: ActionParameterType;
/** parameter name in url */
name: string;
/** placeholder text for the user input field */
label?: string;
/** declare if this field is required (defaults to `false`) */
required?: boolean;
/** regular expression pattern to validate user input client side */
pattern?: string;
/** human-readable description of the `type` and/or `pattern`, represents a caption and error, if value doesn't match */
patternDescription?: string;
/** the minimum value allowed based on the `type` */
min?: string | number;
/** the maximum value allowed based on the `type` */
max?: string | number;
}
/**
* Input field type to present to the user
* @default `text`
*/
export type ActionParameterType =
| "text"
| "email"
| "url"
| "number"
| "date"
| "datetime-local"
| "checkbox"
| "radio"
| "textarea"
| "select";
/**
* note: for ease of reading, this is a simplified type of the actual
*/
interface ActionParameterSelectable extends ActionParameter {
options: Array<{
/** displayed UI label of this selectable option */
label: string;
/** value of this selectable option */
value: string;
/** whether or not this option should be selected by default */
selected?: boolean;
}>;
}
When type is set as select, checkbox, or radio then the Action should include an array of options as shown above in ActionParameterSelectable.
As mentioned in the GET specs, the Blinks Client only supports ActionParameter in the LinkedAction interface, and within ActionParameter, only name, label and required are supported. We're working on bringing complete support as soon as possible
Only Linked Actions Support Parameters
Only linked actions support parameters. The Actions Spec extends Solana Pay and must remain interoperable with Solana Pay. As a result, all URLs that may be called via GET requests must also support POST requests. Parameterized actions are underspecified by construction, and therefore signable transactions are not possible via POST routes.
Blinks with Multi-Input Forms
You can also build a blink with multiple input fields similar to the one in the previous section by a simple change in the structure of the GET response.
The following example demonstrates how you can structure the GET response to allow two different inputs - a custom SOL amount and a Thank You note.
Copy
{
icon: '<image-url>',
label: 'Donate SOL',
title: 'Donate to Alice',
description: 'Cybersecurity Enthusiast | Support my research with a donation.',
links: {
actions: [
{
href: `/api/donate/{${amountParameterName}}/{${thankYouNote}}`,
label: 'Donate',
parameters: [
{
name: amountParameterName,
label: 'Enter a custom SOL amount',
},
{
name: thankYouNote,
label: 'Thank you note',
},
],
},
],
},
}
The Blink would unfurl like this
NOTE: If you have any actions before this action with a label and custom href for predefined amounts of a parameter, it will be ignored when the Blink is unfurled
Previous
Multi-Actions
Next
actions.json
Last updated 1 day ago | https://docs.dialect.to/documentation/actions/specification/action-types | null |
Actions | Actions & Alerts | Actions
Visit Dialect's Dashboard for a step-by-step guide to:
Create your first Action using open source, forkable examples in our Github.
Test your action on https://dial.to.
Register your action.
Share your Actions on Twitter, and bring them to life with Blinks support through your favorite extension like Phantom, Backpack, or Dialect's dedicated Blinks extension.
Building an Action
Actions Providers are just REST APIs, so you can build an Action in any language (JavaScript, TypeScript, Rust, etc.) or any framework (NextJS, Hono, Express, Fastify, etc.) that supports building a REST API. For more details on the Action specification, check out the Specification section of the docs.
In the next section, we cover developing actions with NextJS, a popular framework for developing APIs. If you'd like examples from more languages, please see our Actions repo on Github, where we have examples developed in more frameworks, such as ExpressJS and Hono.
Previous
Blinks
Next
Building Actions with NextJS
Last updated 13 hours ago | https://docs.dialect.to/documentation/actions/actions | null |
Blinks | Actions & Alerts | Blinks
The Actions Spec v1 does not concern itself with visualization or layout, such as image, title, button or input positioning.
This is the responsibility of Blinks. In this section, we describe how blinks are constructed from actions, aspects of Blinks that are affected by the Actions specification, and other matters of design.
Detecting Actions via URL Schemes
Blinks may be linked to Actions in at least 3 ways:
Sharing an explicit Action URL: solana-action://https://actions.alice.com/donate. In this case, only supported clients may render the Blink. There will be no fallback link preview, or site that may be visited outside of the unsupporting client.
Sharing a link to a website that is linked to an actions API via an actions.json file on the website root domain.
E.g. https://alice.com/actions.json maps https://alice.com/donate, a website URL at which users can donate to Alice, to API URL e.g. https://actions.alice.com/donate, at which Actions for donating to Alice are hosted.
Embedding an Action URL in an “interstitial” site or mobile app deep link URL that understands how to parse actions.
E.g. https://dial.to/?action=solana-action:https://actions.alice.com/donate or
https://dial.to/?action=solana-action:https://dial.to/api/donate
If you want to test if your Action URL does indeed unfurl on a Blink, you can paste it into dial.to and it will render the Blink modal.
Testing an action where we included an error
We've included an Action validation tool in there which will parse your API and check if the GET, POST and OPTIONS requests work as required. (It even checks for CORS errors)
Rendering Blinks
Clients that support Blinks should take any of the 3 above formats and correctly unfurl the action directly in the client.
For clients that do not support Blinks, there should be an underlying website. In other words, the browser is the universal fallback.
If a user taps anywhere on a client that is not an action button or text input field, they should be taken to the underlying site.
Option 1 above is the most basic form, but also the most limiting in that unsupported clients have no way to handle the link.
Option 2 is the most advanced, in that the developer has done work to map some site to some action.
Option 3 on the other hand, is the purest manifestation of the actions technology: it fully decouples the action to be taken (the inner URL) from the client in which it’s taken (the outer URL).
We cover Option 3 in greater detail in the next section.
Layout
This section describes how Blinks choose to layout actions based on the types and number of actions returned from an Action API.
It will be filled in soon.
Multi-action
Blinks should support some combination of the above—multiple actions & at most one user input text field—where there may be multiple actions, & user input.
Text fields have a single button associated with them, that requires an input from the user to be clicked. Text fields may not be linked to multiple buttons. (E.g. memo on your vote is not supported by the MVP.)
Render lifecycle
Users should not have to tap anything to render the current state of an action, including any dynamic content or validation state that may be needed. That state is determined when the action is first rendered on the screen.
Chrome extensions bring Blinks to any website
Chrome extensions may be used to add Blink support to clients that would not normally support Blinks. E.g. Twitter web may be made to support Blinks if chrome extensions such as Backpack, Sofllare or Phantom integrate Blinks capabilities.
Interstitial "popup" sites for Blinks
In this section we cover Option 3 above in more detail, as it is the pure URL-encoding of the full experience: specifying both an action and the client in which it is to be executed.
Copy
<interstitial-site-or-deeplink-url>/?action=solana:<action-url>
Interstitials—
Interstitial URLs are website or mobile app deep link URLs specifying a client in which to sign for an action. Examples include wallets or other wallet-related applications that are typically responsible for storing keypairs, and that are capable of giving user signing experiences.
https://dial.to
https://backpack.app
https://solflare.com
https://phantom.app
https://tiplink.io
https://fusewallet.com
Any signing client can implement an interstitial site for execution, and developers and users can compose interstitials and actions as they see fit. We describe some examples in the next section.
User journeys—
Alice is using Jupiter to swap tokens. She chooses the paying & receiving tokens, say SOL & WIF. Near the Swap button is another button she may press, that allows for sharing the action with others.
When she presses it, she is presented with a sheet in which she can choose the signing client. It’s a CTA like “Sign with…” and then a grid of well-known wallets or key holding apps like Phantom, Backpack, Solflare, Tiplink, etc.
Once she chooses one, say Backpack, it copies to her clipboard a URL of the format https://backpack.app/?action=solana:<swap-url>
Determining interstitials—
Note that in the above example, jup.ag’s interface gives Alice choice for the interstitial, not the blink itself. When Bob taps Alice’s choice for backpack, he is taken to Backpack.
💡 If for example Dialect chose to implement an interstitial-choosing step at https://dialect.to/?action=… —where a user chooses which signing client to use—Backpack, Phantom, etc.—then this is an entirely different abstraction than an interstitial URL, and not a part of the official Blink implementation.
Execution & lifecycle
When one action is being taken from a set of available actions, all other actions become un-executable until such time as the current executing action succeeds or fails (incl. timeout).
In future versions, this may no longer be true, and more flexible experiences may be created.
Blinks do not need to persist their lifecycle beyond the in-the-moment, single user session. If a user refreshes the client, or leaves and comes back at a later time, past or current interactions with the Blink are no longer reflected by the client. This includes not just succeeded actions, but also actions in the middle of execution.
In future versions, Action and Blink outcomes may persist beyond single-session use.
Previous
actions.json
Next
Actions
Last updated 10 days ago | https://docs.dialect.to/documentation/actions/specification/blinks | null |
Building Actions with NextJS | Actions & Alerts | Building Actions with NextJS
In this section, you'll learn how to build a Solana Action. For the sake of this documentation, we'll be using NextJS to build it.
For code examples of Actions, check out our code examples or Solana Developers' code examples.
Codebase setup
Create a Next app through the CLI command and the subsequent setup questions on the CLI
Copy
npx create-next-app <your-action-codebase-name>
cd <your-action-codebase-name>
Within src/app, create a directory called api/actions and within that, create a folder with the name of the action you want to create (eg: api/actions/donate-sol) with a route.ts file. Now, your file directory should look like this:
The route.ts is the file that has the Action API logic which we're going to look at in a bit.
Before we dive into the API logic, install the Solana Actions SDK by running the following command:
Copy
# npm
npm i @solana/actions
#yarn
yarn add @solana/actions
Importing the Actions SDK
At the top of the file, you need to import the following from the @solana/actions SDK:
Copy
import {
ActionPostResponse,
ACTIONS_CORS_HEADERS,
createPostResponse,
ActionGetResponse,
ActionPostRequest,
} from "@solana/actions";
Structuring the GET & OPTIONS Request
The metadata of an Action is returned when a GET request is submitted to the Action API endpoint through a payload. For the complete scope of the payload, check out the GET Request specifications.
Then, the payload is sent in the GET response along with the CORS Headers for it. For more details on why CORS is required, check out the CORS specifications.
The basic structure of the GET request with the payload is:
Copy
export const GET = async (req: Request) => {
const payload: ActionGetResponse = {
title: "Actions Example - Simple On-chain Memo",
icon: 'https://ucarecdn.com/7aa46c85-08a4-4bc7-9376-88ec48bb1f43/-/preview/880x864/-/quality/smart/-/format/auto/',
description: "Send a message on-chain using a Memo",
label: "Send Memo",
};
return Response.json(payload, {
headers: ACTIONS_CORS_HEADERS,
});
}
The payload here contains the bare minimum metadata that can be returned by an Action's GET request. The example above is a simple Action for sending a memo transaction to a predefined wallet address.
Linked Actions
The actions specification allows for multiple actions to be served via a single Action URL. To do this, the payload must include a links field which has a list of actions that are to be included. For further reading into the full scope of the links field, check out the Multi-Actions specifications.
The payload can be structured in a way that has either - a single input with it's own button, multiple inputs each having their own button to submit a transaction, or multiple inputs with a single button at the bottom to submit a transaction. This is done by varying the structure of the links.actions field
Multiple Inputs - Single Button
Copy
const payload: ActionGetResponse = {
title: 'Donate to Alice',
icon: '<image-url>',
label: 'Donate SOL',
description: 'Cybersecurity Enthusiast | Support my research with a donation.',
links: {
actions: [
{
href: `/api/donate/{${amountParameterName}}/{${thankYouNote}}`,
label: 'Donate',
parameters: [
{
name: amountParameterName,
label: 'Enter a custom SOL amount',
},
{
name: thankYouNote,
label: 'Thank you note',
},
],
},
],
},
}
Multiple Inputs - Multiple Buttons
Copy
const payload: ActionGetResponse ={
title: 'Donate to Alice',
icon: '<image-url>',
label: 'Donate SOL',
description: 'Cybersecurity Enthusiast | Support my research with a donation.',
"links": {
"actions": [
{
"label": "1 SOL", // button text
"href": "/api/donate?amount=10"
// no `parameters` therefore not a text input field
},
{
"label": "5 SOL", // button text
"href": "/api/donate?amount=100"
// no `parameters` therefore not a text input field
},
{
"label": "10 SOL", // button text
"href": "/api/donate?amount=1000"
// no `parameters` therefore not a text input field
},
{
"label": "Donate", // button text
"href": "/api/donate?amount={amount}",
"parameters": [
{
"name": "amount", // field name
"label": "Enter a custom SOL amount" // text input placeholder
}
]
}
]
}
};
OPTIONS request
The OPTIONS request whose CORS Headers are required for CORS Handling by clients that unfurl Actions is done as follows:
Copy
export const OPTIONS = GET;
POST request
Users then execute an Action through a POST request sent to either the Action URL itself or one of the linked Action URLs.
The body of the POST request contains the wallet address that connects to the client that unfurls the Action and can be derived using the following line of code:
The basic structure of the POST request with the payload is:
Copy
export const POST = async (req: Request) => {
const body: ActionPostRequest = await req.json();
// insert transaction logic here
const payload: ActionPostResponse = await createPostResponse({
fields: {
transaction,
message: "Optional message to include with transaction",
},
});
return Response.json(payload, {
headers: ACTIONS_CORS_HEADERS,
});
};
A transaction to be signed by the user is returned through the payload when a POST request is submitted to the Action API Endpoint. The payload consists of a transaction and an optional message. For the full scope of the POST request and response, check out the full POST specifications
The transaction included in an Action can be any transaction that can be executed on the Solana blockchain. The most common libraries used for the transaction logic are @solana/web3.js and @metaplex-foundation/umi.
Now, it is fully the responsibility of the client to sign the transaction and submit it to the blockchain. The Dialect Blinks SDK manages the UI unfurling and execution lifecycle of the Action.
For more examples on building Actions, check out the various open-source examples on our Github, including those for various ecosystem partners like Helius, Jupiter, Meteora, Sanctum and Tensor.
Previous
Actions
Next
Blinks
Last updated 8 days ago | https://docs.dialect.to/documentation/actions/actions/building-actions-with-nextjs | [
"npx create-next-app <your-action-codebase-name>cd <your-action-codebase-name>",
"npm i @solana/actions yarn add @solana/actions",
"import {ActionPostResponse,ACTIONS_CORS_HEADERS,createPostResponse,ActionGetResponse,ActionPostRequest,} from @solana/actions;",
"export const GET = async (req: Request) => {const payload: ActionGetResponse = {title: Actions Example - Simple On-chain Memo,icon: https://ucarecdn.com/7aa46c85-08a4-4bc7-9376-88ec48bb1f43/-/preview/880x864/-/quality/smart/-/format/auto/,description: Send a message on-chain using a Memo,label: Send Memo,};return Response.json(payload, {headers: ACTIONS_CORS_HEADERS,});}",
"const payload: ActionGetResponse = {title: Donate to Alice,icon: <image-url>,label: Donate SOL,description: Cybersecurity Enthusiast | Support my research with a donation.,links: {actions: [{href: /api/donate/{${amountParameterName}}/{${thankYouNote}},label: Donate,parameters: [{name: amountParameterName,label: Enter a custom SOL amount,},{name: thankYouNote,label: Thank you note,},],},],},}",
"const payload: ActionGetResponse ={title: Donate to Alice,icon: <image-url>,label: Donate SOL,description: Cybersecurity Enthusiast | Support my research with a donation.,links: {actions: [{label: 1 SOL,href: /api/donate?amount=10},{label: 5 SOL,href: /api/donate?amount=100},{label: 10 SOL,href: /api/donate?amount=1000},{label: Donate, href: /api/donate?amount={amount},parameters: [{name: amount, label: Enter a custom SOL amount}]}]}};",
"export const OPTIONS = GET;",
"export const POST = async (req: Request) => {const body: ActionPostRequest = await req.json(); const payload: ActionPostResponse = await createPostResponse({fields: {transaction,message: Optional message to include with transaction,},});return Response.json(payload, {headers: ACTIONS_CORS_HEADERS,});};"
] |
Blinks | Actions & Alerts | Blinks
In the following sections, you can find how to add native blink support to your dApps through our React SDK, React Native SDK or even adding blink support to 3rd party sites through a Chrome extension.
If you've built an Action API and want to test the unfurling on an interstitial site, visit our Blinks specification for more details
Adding Blinks to non-React codebases
If you are interested in adding Blinks, reach out to us on our Discord.
Previous
Building Actions with NextJS
Next
Add blinks to your web app
Last updated 7 days ago | https://docs.dialect.to/documentation/actions/blinks | null |
Add blinks to 3rd party sites via your Chrome extension | Actions & Alerts | Add blinks to 3rd party sites via your Chrome extension
This section is for Chrome extension developers who want to add Blinks to third party sites like Twitter. If you're interested in Native blink support check out our React SDK or React Native SDK.
Copy
// contentScript.ts
import { setupTwitterObserver } from "@dialectlabs/blinks/ext/twitter";
import { ActionConfig, ActionContext } from "@dialectlabs/blinks";
// your RPC_URL is used to create a connection to confirm the transaction after action execution
setupTwitterObserver(new ActionConfig(RPC_URL, {
signTransaction: async (tx: string, context: ActionContext) => { ... },
connect: async (context: ActionContext) => { ... }
}))
// or
import { type ActionAdapter } from "@dialectlabs/blinks";
class MyActionAdapter implements ActionAdapter {
async signTransaction(tx: string, context: ActionContext) { ... }
async connect(context: ActionContext) { ... }
async confirmTransaction(sig: string, context: ActionContext) { ... }
}
setupTwitterObserver(new MyActionAdapter());
Previous
Add blinks to your mobile app
Next
Security
Last updated 7 days ago | https://docs.dialect.to/documentation/actions/blinks/add-blinks-to-3rd-party-sites-via-your-chrome-extension | [
"import { setupTwitterObserver } from @dialectlabs/blinks/ext/twitter;import { ActionConfig, ActionContext } from @dialectlabs/blinks;setupTwitterObserver(new ActionConfig(RPC_URL, {signTransaction: async (tx: string, context: ActionContext) => { ... },connect: async (context: ActionContext) => { ... }}))import { type ActionAdapter } from @dialectlabs/blinks;class MyActionAdapter implements ActionAdapter {async signTransaction(tx: string, context: ActionContext) { ... }async connect(context: ActionContext) { ... }async confirmTransaction(sig: string, context: ActionContext) { ... }}setupTwitterObserver(new MyActionAdapter());"
] |
Add blinks to your mobile app | Actions & Alerts | Add blinks to your mobile app
This section covers adding blinks directly to your React Native dApp through our React Native SDK for blinks. The SDK is completely open-source and can be found in our Github.
Installation
Copy
# npm
npm i @dialectlabs/blinks @dialectlabs/blinks-react-native
#yarn
yard add @dialectlabs/blinks @dialectlabs/blinks-react-native
Adding the Blink Component
The following imports need to be made to simplify the blink integration
useAction hook and ActionAdapter type from @dialectlabs/blinks
Blink component from @dialectlabs/blinks-react-native
Basic Usage:
A getWalletAdapter function has to be defined to generate an adapter of type ActionAdapter for interactions with user wallets like wallet connect and signing transactions through the React Native dApp.
After that, the <Blink /> component can be used in the React Native dApp to render the blink. It takes the following props:
theme - has the styling for the blink to be rendered
action - object returned from useAction function (which requires the adapter from getWalletAdapter and Action URL)
websiteUrl - the complete URL of the Action
websiteText - the domain name of the Action URL
Copy
import { useAction, type ActionAdapter } from '@dialectlabs/blinks';
import { Blink } from '@dialectlabs/blinks-react-native';
import { PublicKey } from '@solana/web3.js';
import type React from 'react';
function getWalletAdapter(): ActionAdapter {
return {
connect: async (_context) => {
console.log('connect');
return PublicKey.default.toString();
},
signTransaction: async (_tx, _context) => {
console.log('signTransaction');
return {
signature: 'signature',
};
},
confirmTransaction: async (_signature, _context) => {
console.log('confirmTransaction');
},
};
}
export const BlinkInTheWalletIntegrationExample: React.FC<{
url: string; // could be action api or website url
}> = ({ url }) => {
const adapter = getWalletAdapter();
const { action } = useAction({ url, adapter });
if (!action) {
// return placeholder component
}
const actionUrl = new URL(url);
return (
<Blink
theme={{
'--blink-button': '#1D9BF0',
'--blink-border-radius-rounded-button': 9999,
// and any other custom styles
}}
action={action}
websiteUrl={actionUrl.href}
websiteText={actionUrl.hostname}
/>
);
};
Customize Blink Styles
The blink styles can be customized by passing a theme prop to the Blink component. The theme object can contain any of the following properties:
Copy
--blink-bg-primary: #202327;
--blink-button: #1d9bf0;
--blink-button-disabled: #2f3336;
--blink-button-success: #00ae661a;
--blink-icon-error: #ff6565;
--blink-icon-primary: #6e767d;
--blink-icon-warning: #ffb545;
--blink-input-bg: #202327;
--blink-input-stroke: #3d4144;
--blink-input-stroke-disabled: #2f3336;
--blink-input-stroke-error: #ff6565;
--blink-input-stroke-selected: #1d9bf0;
--blink-stroke-error: #ff6565;
--blink-stroke-primary: #1d9bf0;
--blink-stroke-secondary: #3d4144;
--blink-stroke-warning: #ffb545;
--blink-text-brand: #35aeff;
--blink-text-button: #ffffff;
--blink-text-button-disabled: #768088;
--blink-text-button-success: #12dc88;
--blink-text-error: #ff6565;
--blink-text-input: #ffffff;
--blink-text-input-disabled: #566470;
--blink-text-input-placeholder: #6e767d;
--blink-text-link: #6e767d;
--blink-text-primary: #ffffff;
--blink-text-secondary: #949ca4;
--blink-text-success: #12dc88;
--blink-text-warning: #ffb545;
--blink-transparent-error: #aa00001a;
--blink-transparent-grey: #6e767d1a;
--blink-transparent-warning: #a966001a;
--blink-border-radius-rounded-lg: 0.25rem;
--blink-border-radius-rounded-xl: 0.5rem;
--blink-border-radius-rounded-2xl: 1.125rem;
--blink-border-radius-rounded-button: 624.9375rem;
--blink-border-radius-rounded-input: 624.9375rem;
Using these CSS classes, you can customize the styles to fit the UI of your application.
Previous
Add blinks to your web app
Next
Add blinks to 3rd party sites via your Chrome extension
Last updated 1 day ago | https://docs.dialect.to/documentation/actions/blinks/add-blinks-to-your-mobile-app | [
"npm i @dialectlabs/blinks @dialectlabs/blinks-react-nativeyard add @dialectlabs/blinks @dialectlabs/blinks-react-native",
"import { useAction, type ActionAdapter } from @dialectlabs/blinks;import { Blink } from @dialectlabs/blinks-react-native;import { PublicKey } from @solana/web3.js;import type React from react;function getWalletAdapter(): ActionAdapter {return {connect: async (_context) => {console.log(connect);return PublicKey.default.toString();},signTransaction: async (_tx, _context) => {console.log('signTransaction');return {signature: signature,};},confirmTransaction: async (_signature, _context) => {console.log(confirmTransaction);},};}export const BlinkInTheWalletIntegrationExample: React.FC<{url: string; // could be action api or website url}> = ({ url }) => {const adapter = getWalletAdapter();const { action } = useAction({ url, adapter });if (!action) {}const actionUrl = new URL(url);return (<Blinktheme={{--blink-button: #1D9BF0,--blink-border-radius-rounded-button: 9999,}}action={action}websiteUrl={actionUrl.href}websiteText={actionUrl.hostname}/>);};"
] |
Security | Actions & Alerts | Security
Actions and Blinks are a new way to interact with crypto transactions. They present both exciting new opportunities as well as new attack vectors for bad actors. Safety is high priority for this new technology.
As a public good for the Solana ecosystem, Dialect maintains a public registry — together with the help of Solana Foundation and other community members — of blockchain links that have been verified as non-malicious. As of launch, only Actions that have been registered in the Dialect registry will unfurl in the Twitter feed when posted. Learn how to apply to the Registry here.
In the near term, the Registry will be managed and hosted at https://dial.to/registry, where developers may register their actions as trusted, and malicious actions will be flagged as blocked.
Why a new registry is needed
Wallet Chrome extensions typically rely on the origin URL of the web page from which a transaction is being created to determine whether that transaction is trustworthy. Actions break this mould, and make it possible, and common, for transactions coming from providers not affiliated with the site.
Registration status
Wallets and other clients using Dialect's Blinks SDK use the registry hosted at https://dial.to/registry to check URLs in the client, and then render Blinks as one of:
trusted—This action has been registered by the developer and accepted by the registration committee.
blocked—This action has been flagged as malicious by the registration community.
none—The action has not been registered.
Users should still take precaution when executing actions, trusted or otherwise. Even trusted actions may cause unintended consequences—the developer may bugs in their action that cause unintended outcomes for users, or their Actions Provider may get compromised by a third party.
Rendering Blinks according to Registry status
Wallets that use Dialect's Blinks clients will use this registry under the hood to decide how to render Blinks. They have two options:
Render the Blink with the appropriate registry status. Either neutral for trusted, yellow with a warning for unregistered actions with status none, and red for blocked actions known to be malicious.
Don't render blinks of specific registry statuses.
Today, Phantom, Backpack, and all known wallets implementing Blinks clients for sites such as Twitter have chosen to implement option 2. This is because not rendering a Blink that is of status none or blocked is the most conservative thing a Blinks client can do. Neither Phantom, Backpack nor Dialect are in the business of deciding what links users can share on a independent site such as Twitter.
Register your Action
Submit your action to the Registry here: https://dial.to/register.
Please complete the following steps to ensure your submission contains accurate information:
Step 1—Your Action Works ✔️
Ensure your action performs all tasks correctly and reliably. Thoroughly test it to confirm functionality and avoid rejection. You can test your action at dial.to
Step 2—Have a Clear Action Description 📝
Provide a clear, detailed description to expedite the review process. A well-matched description and functionality help reviewers approve your action quickly.
Step 3—Test your Action Thoroughly 🧪
Thoroughly test your action in various environments. Consistency and reliability can speed up approval.
Step 4—Build Secure Actions 🔒
Adhere to best security practices to ensure your action is approved. Prioritize security to protect users and gain approval swiftly.
Step 5—Provide a Valid Contact 📞
Provide accurate contact information for smooth follow-ups and verification. Keeping your contacts updated helps prevent delays.
Step 6— Patience 🙏
We are on a mission to change how experiences are shared on the internet, & are thrilled to have you along for the ride
Currently registration review is a manual process, however, we are working toward a future automated registration review process.
Registry schedule
Thank you for your patience as we work to better automate and decentralize the Actions registry.
Registry submissions may be made at any time. Applications will be approved during business hours in various time zones, Monday through Friday.
Work with us on the Registry
Dialect believes trust is never something that can be managed by a centralized authority. In the long term, we are working to create a more decentralized, community-driven system for trust. If you're interested in working on this with us, reach out to us in our community Discord.
Previous
Add blinks to 3rd party sites via your Chrome extension
Next
The Blinks Public Registry
Last updated 1 month ago | https://docs.dialect.to/documentation/actions/security | null |
The Blinks Public Registry | Actions & Alerts | The Blinks Public Registry
We have made our Blinks Public Registry easily accessible through an API endpoint, and in a beautiful new interface on https://dial.to. Running a GET request on the endpoint will return JSON data of all the action APIs that have been submitted, registered and blocked from the registry
The Blinks Public Registry API can be called from https://registry.dial.to/v1/list.
Copy
curl -X GET https://registry.dial.to/v1/list
Sending the GET request to this endpoint returns a 200 response with the data in the following format:
Copy
{
results: Array<{
actionUrl: string;
blinkUrl?: string;
websiteUrl?: string;
createdAt: string;
tags: string[];
}>
}
The fields within each element of the results array are:
actionUrl - The URL of the Action.
blinkUrl - (optional) The Webpage or Interstitial URL that points to the Action URL
websiteUrl - (optional) URL of the Action owner.
createdAt - When the Action was added to the registry.
tags - The tags depicting the Action's status on the registry.
Browse the Public Registry at dial.to
All blinks on the public registry are now discoverable right on https://dial.to, where blinks can be filtered by registration status.
Previous
Security
Next
Alerts
Last updated 18 days ago | https://docs.dialect.to/documentation/actions/the-blinks-public-registry | null |
Alerts | Actions & Alerts | Alerts
Dialect Alerts is a smart messaging protocol for dapp notifications and wallet-to-wallet chat. We are powering notifications and messaging for over 30 of the most-loved dapps and wallets on Solana, EVM and Aptos.
All of our tooling is open source and free to use. Our on-chain messaging protocol, v0, is live & audited on mainnet. We offer a host of off-chain tooling and services as well, including a multi-chain messaging protocol, v1, and a set of tools around powering notifications for dapps.
How to use this documentation
This documentation is meant for developers who wish to integrate Dialect into their dapps or wallets for messaging and notifications. All our tooling is available in our Github; this documentation will guide you through the relevant repos.
See the Getting started section for more information.
Previous
The Blinks Public Registry
Next
Getting started
Last updated 14 days ago | https://docs.dialect.to/documentation/alerts | null |
Alerts Quick Start | Actions & Alerts | Alerts Quick Start
An end-to-end guide on setting up notifications for your dapp.
This section provides an end-to-end quick start guide to get set up sending notifications to your users from your dapp. We get you set up for production use by walking through the following steps:
Create and configure your dapp keypair, which you use to send notifications.
Add our notifications component to your front end, for users to register and receive the notifications from you.
Send dapp notifications from your backend.
Try a live example of this notification bell at https://alerts-example.dialect.to.
Create Your Dapp Keypair
Dialect's protocol enables communication between wallets. Dapp notifications are no exception. To send notifications to user wallets, dapps should first create a keypair for messaging.
Create keypairs for your dapp and for a test user. For your test user, you may also use existing test keypairs you have, as this keypair will eventually get added to a chrome extension wallet such as Phantom for testing our front end component libraries.
We recommend using the Solana CLI to create a new keypair.
Copy
// Create a dapp keypair
solana-keygen new -o <insert-dapp-name>-messaging-keypair.json
solana-keygen publickey <insert-dapp-name>-messaging-keypair.json > dapp-pubkey.pub
// [OPTIONAL] Create a test user keypair (or use one you already have in Phantom or another chrome extension wallet)
solana-keygen new -o test-user-messaging-keypair.json
DO NOT share your dapp private key with anyone, not even Dialect. We never store your private key anywhere in our systems, and will never ask for it. It is for you and your use alone.
You'll need the public and private keys of this keypair in the following sections.
Register Your Keypair as a Dapp to Send Notifications
Create a Dialect SDK instance
In the following sections you'll execute code from Dialect's typescript SDK. First set up your preferred node and typescript environment. Then install & import Dialect SDK dependencies, and create a Dialect SDK instance.
Install React and SDK Dependencies
In this section you'll install Dialect and Solana dependencies for both the front end and backend requirements. You'll then use the backend dependencies to create a Dialect SDK instance, which you will use to register your keypair as a dapp in our system.
Prerequisites
The documentation assumes that you already have @solana/web3.js installed and configured in your backend app
Install dependencies
In order to start adding messaging functionality to your web dapp, we need to install a few essential packages first
npm:
Copy
npm install @solana/wallet-adapter-base --save
npm install @dialectlabs/sdk --save
npm install @dialectlabs/blockchain-sdk-solana --save
yarn:
Copy
yarn add @solana/wallet-adapter-base
yarn add @dialectlabs/sdk
yarn add @dialectlabs/blockchain-sdk-solana
Set DIALECT_SDK_CREDENTIALS environment variable to your dapp's Solana keypair, generated above
Copy
import {
Dialect,
DialectCloudEnvironment,
DialectSdk,
} from '@dialectlabs/sdk';
import {
Solana,
SolanaSdkFactory,
NodeDialectSolanaWalletAdapter
} from '@dialectlabs/blockchain-sdk-solana';
const environment: DialectCloudEnvironment = 'production';
const sdk: DialectSdk<Solana> = Dialect.sdk(
{
environment,
},
SolanaSdkFactory.create({
// IMPORTANT: must set environment variable DIALECT_SDK_CREDENTIALS
// to your dapp's Solana keypair e.g. [170,23, . . . ,300]
wallet: NodeDialectSolanaWalletAdapter.create(),
}),
);
Register your dapp
Register your dapp keypair, so user keypairs can then register to and then receive notifications from you.
Head to https://dashboard.dialect.to, connect your dapps’ wallet and register your Dapp name and Description to get started sending notifications.
You'll use this same SDK setup and configuration in your backend to send dapp notifications, as described below in Send notifications from your backend.
But first, let's add the notification bell to your react app, where you'll be able to subscribe for notifications and then receive them as a test user.
Add the Dialect Bell React Component to Your Front End
Dialect's @dialectlabs/react-ui library provides out-of-the-box react components for embedding a notification bell in your react app, from which your users can fully manage their notifications experience with you. It is a pre-built, themeable, self-sufficient and opinionated set of UI components for your users that abstracts away a large amount of notifications logic for you as a developer. Specifically, it handles:
Registration for in-app, email, and Telegram notifications, including full email and Telegram verification flows.
Registration for any number of notification types you choose to create. This could be price alerts, liquidation warnings, NFT bid events, or anything else you can dream up.
In-app feed of notifications, including a badge on the notification bell to let your users know when they have unread notifications.
We strongly recommend you use our react components to manage your client experience for your users in your dapp. These components are fully stylable to your brand, and will reduce your implementation time by 80% or more.
All you need to do as a developer is add this component to your react app, and the rest comes out of the box. Let's go through adding this component to your app.
Prerequisites
The documentation assumes that you already have solana wallet adapter installed and configured in your app
Follow wallet adapter guide to install it https://github.com/anza-xyz/wallet-adapter/blob/master/APP.md
Install dependencies
In order to start adding messaging functionality to your web dapp, we need to install a few essential packages first.
npm:
Copy
npm add @dialectlabs/react-ui @dialectlabs/react-sdk-blockchain-solana
yarn:
Copy
yarn add @dialectlabs/react-ui @dialectlabs/react-sdk-blockchain-solana
Add the Dialect Notifications Component to your app
You are now ready to add the Dialect notification bell react component to your app. To do this, let's first create a separate component in your project and call it DialectNotificationComponent that contains the code below. Specifically, this code:
Import styles from the Dialect UI library
ConfiguresDialectSolanaSdk which integrates with the wallet adapter
Adds a notifications button
Set DAPP_ADDRESS variable to the public key generated in previous section
To do the above, add this file to your project:
Copy
/* DialectNotificationComponent.tsx */
'use client';
import '@dialectlabs/react-ui/index.css';
import { DialectSolanaSdk } from '@dialectlabs/react-sdk-blockchain-solana';
import { NotificationsButton } from '@dialectlabs/react-ui';
/* Set DAPP_ADDRESS variable to the public key generated in previous section */
const DAPP_ADDRESS = '...';
export const DialectNotificationComponent = () => {
return (
<DialectSolanaSdk dappAddress={DAPP_ADDRESS}>
<NotificationsButton />
</DialectSolanaSdk>
);
};
Now import this file into your main navbar component, as described in the next section.
Use your new DialectNotificationComponent in your navbar
Once you've configured your project with Dialect context providers as described in the previous section, you can simply drop in the Dialect Notifications react component.
Copy
/* App.tsx */
import {
ConnectionProvider,
WalletProvider
} from '@solana/wallet-adapter-react';
import { DialectNotificationComponent } from '<wherever-you-created-the-file-above>';
const App = () => {
return (
// We're using @solana/wallet-adapter-react package for wallet api
// Assuming WalletProvider and ConnectionProvider are properly configured with necessary wallets and network.
<ConnectionProvider endpoint={endpoint}>
<WalletProvider wallets={wallets} autoConnect>
{/* Your app's components go here, nested within the context providers. */}
<DialectNotificationComponent />
</WalletProvider>
</ConnectionProvider>
);
}
You're all set! Run your app now and use the notification bell to register for notifications for whichever test user wallet you'd like.
You will begin sending notifications to that test user in the next section.
Customizing the Dialect Notification Component Themes
Advancing React Notifications
Styling Notifications widget
See our example app in our react-ui repo:
To see a complete working example of our notifications bell check out the example nextjs app in our react component library. You can run this example like you would any nextjs application, as described from that library.
Send notifications from your backend
Now that you have a notification bell and modal in your react app, let's use the dapp keypair we created above to begin sending notifications to users.
If you haven't already, make sure you've registered your dapp keypair (see Register your dapp).
And then create a Dialect SDK instance (see Create a Dialect SDK instance).
Start sending messages
With your SDK instance, you can now run the following code to send a notification to all subscribed users.
Copy
const dapp = await sdk.dapps.find();
await dapp.messages.send({
title: 'Hello from Dialect',
message: 'Hello from the Dialect quick start guide example.',
actionsV2: {
type: DappMessageActionType.LINK,
links: [
{
label: 'Open Dialect Quick Start',
url: 'https://docs.dialect.to/documentation',
},
],
}
});
If you've registered to receive notifications from your app, this notification should now appear in your notification modal.
Advanced setup
This concludes the quick start guide. To do more advanced things like
sending notifications to specific wallets, or sets of wallets,
setting up notification types, or
sending notifications for specific notification types,
see the Notifications section for more info.
Previous
Getting started
Next
Alerts & Monitoring
Last updated 3 months ago | https://docs.dialect.to/documentation/alerts/alerts-quick-start | null |
Add blinks to your web app | Actions & Alerts | Add blinks to your web app
This section covers adding Blinks directly to your React dapp using our Blinks React SDK. The SDK is open-source and can be found in our Github.
Installation
Copy
# npm
npm i @dialectlabs/blinks
#yarn
yard add @dialectlabs/blinks
Adding the Blink Component
The following hooks are exported from @dialectlabs/blinks/react in order to simplify the integration.
useAction - overall hook: fetches the action, sets up an adapter, inits registry and refreshes it every 10 minutes
useActionsRegistry - fetches the registry and refreshes it
useActionSolanaWalletAdapter - sets up an adapter for Action using wallet provider
If you want to build your own hooks, use Action , ActionsRegistry and ActionConfig/ActionAdapter classes and interfaces.
If you are using the useActionSolanaWalletAdapter hook, then be sure to have<WalletProvider />and<WalletModalProvider /> above in the component tree.
Basic Usage:
Copy
import '@dialectlabs/blinks/index.css';
import { useState, useEffect } from 'react';
import { Action, Blink, ActionsRegistry } from "@dialectlabs/blinks";
import { useAction } from '@dialectlabs/blinks/react';
// needs to be wrapped with <WalletProvider /> and <WalletModalProvider />
const App = () => {
const [action, setAction] = useState<Action | null>(null);
const actionApiUrl = '...';
// useAction initiates registry, adapter and fetches the action.
const { adapter } = useActionSolanaWalletAdapter('<YOUR_RPC_URL_OR_CONNECTION>');
const { action } = useAction(actionApiUrl, adapter);
return action ? <Blink action={action} websiteText={new URL(actionApiUrl).hostname} /> : null;
}
Advanced:
Copy
import '@dialectlabs/blinks/index.css';
import { useState, useEffect } from 'react';
import { Action, Blink, ActionsRegistry, type ActionAdapter } from "@dialectlabs/blinks";
import { useAction, useActionsRegistryInterval } from '@dialectlabs/blinks/react';
// needs to be wrapped with <WalletProvider /> and <WalletModalProvider />
const App = () => {
// SHOULD be the only instance running (since it's launching an interval)
const { isRegistryLoaded } = useActionsRegistryInterval();
const { adapter } = useActionSolanaWalletAdapter('<YOUR_RPC_URL_OR_CONNECTION>');
return isRegistryLoaded ? <ManyActions adapter={adapter} /> : null;
}
const ManyActions = ({ adapter }: { adapter: ActionAdapter }) => {
const apiUrls = useMemo(() => (['...', '...', '...']), []);
const [actions, setActions] = useState<Action[]>([]);
useEffect(() => {
const fetchActions = async () => {
const promises = apiUrls.map(url => Action.fetch(url).catch(() => null));
const actions = await Promise.all(promises);
setActions(actions.filter(Boolean) as Action[]);
}
fetchActions();
}, [apiUrls]);
// we need to update the adapter every time, since it's dependent on wallet and walletModal states
useEffect(() => {
actions.forEach((action) => action.setAdapter(adapter));
}, [actions, adapter]);
return actions.map(action => (
<div key={action.url} className="flex gap-2">
<Blink action={action} websiteText={new URL(action.url).hostname} />
</div>
);
}
Customize Blink Styles
Dialect's Blinks SDK supports customizable styles so you can render Blinks that match the style of your dApp or 3rd party site, such as Twitter.
To render a Blink with a preset pass stylePreset prop (defaults to default which is the dial.to theme) to <Blink /> component:
Copy
import { Blink } from '@dialectlabs/blinks';
...
return <Blink stylePreset="x-dark" ... />;
Style presets are mapped to classes the following way:
x-dark -> .x-dark
x-light -> .x-light
default -> .dial-light
custom -> .custom
To override a certain preset use the following CSS Variables:
Copy
/*
Use .x-dark, .x-light, .dial-light, or .custom classes
.custom - does not contain any colors, radii or shadow
*/
.blink.x-dark {
--blink-bg-primary: #202327;
--blink-button: #1d9bf0;
--blink-button-disabled: #2f3336;
--blink-button-hover: #3087da;
--blink-button-success: #00ae661a;
--blink-icon-error: #ff6565;
--blink-icon-error-hover: #ff7a7a;
--blink-icon-primary: #6e767d;
--blink-icon-primary-hover: #949ca4;
--blink-icon-warning: #ffb545;
--blink-icon-warning-hover: #ffc875;
--blink-input-bg: #202327;
--blink-input-stroke: #3d4144;
--blink-input-stroke-disabled: #2f3336;
--blink-input-stroke-error: #ff6565;
--blink-input-stroke-hover: #6e767d;
--blink-input-stroke-selected: #1d9bf0;
--blink-stroke-error: #ff6565;
--blink-stroke-primary: #1d9bf0;
--blink-stroke-secondary: #3d4144;
--blink-stroke-warning: #ffb545;
--blink-text-brand: #35aeff;
--blink-text-button: #ffffff;
--blink-text-button-disabled: #768088;
--blink-text-button-success: #12dc88;
--blink-text-error: #ff6565;
--blink-text-error-hover: #ff7a7a;
--blink-text-input: #ffffff;
--blink-text-input-disabled: #566470;
--blink-text-input-placeholder: #6e767d;
--blink-text-link: #6e767d;
--blink-text-link-hover: #949ca4;
--blink-text-primary: #ffffff;
--blink-text-secondary: #949ca4;
--blink-text-success: #12dc88;
--blink-text-warning: #ffb545;
--blink-text-warning-hover: #ffc875;
--blink-transparent-error: #aa00001a;
--blink-transparent-grey: #6e767d1a;
--blink-transparent-warning: #a966001a;
--blink-border-radius-rounded-lg: 0.25rem;
--blink-border-radius-rounded-xl: 0.5rem;
--blink-border-radius-rounded-2xl: 1.125rem;
--blink-border-radius-rounded-button: 624.9375rem;
--blink-border-radius-rounded-input: 624.9375rem;
/* box-shadow */
--blink-shadow-container: 0px 2px 8px 0px rgba(59, 176, 255, 0.22), 0px 1px 48px 0px rgba(29, 155, 240, 0.24);
}
Be sure to override with CSS Specificity in mind or by import order
Using these CSS classes, you can customize the styles to fit the UI of your application.
Previous
Blinks
Next
Add blinks to your mobile app
Last updated 7 days ago | https://docs.dialect.to/documentation/actions/blinks/add-blinks-to-your-web-app | [
"import '@dialectlabs/blinks/index.css';import { useState, useEffect } from 'react';import { Action, Blink, ActionsRegistry } from @dialectlabs/blinks;import { useAction } from '@dialectlabs/blinks/react';const App = () => {const [action, setAction] = useState<Action | null>(null);const actionApiUrl = '...';const { adapter } = useActionSolanaWalletAdapter('<YOUR_RPC_URL_OR_CONNECTION>');const { action } = useAction(actionApiUrl, adapter);return action ? <Blink action={action} websiteText={new URL(actionApiUrl).hostname} /> : null;}",
"import '@dialectlabs/blinks/index.css';import { useState, useEffect } from 'react';import { Action, Blink, ActionsRegistry, type ActionAdapter } from @dialectlabs/blinks;import { useAction, useActionsRegistryInterval } from '@dialectlabs/blinks/react';const App = () => {const { isRegistryLoaded } = useActionsRegistryInterval();const { adapter } = useActionSolanaWalletAdapter('<YOUR_RPC_URL_OR_CONNECTION>');return isRegistryLoaded ? <ManyActions adapter={adapter} /> : null;}const ManyActions = ({ adapter }: { adapter: ActionAdapter }) => {const apiUrls = useMemo(() => (['...', '...', '...']), []);const [actions, setActions] = useState<Action[]>([]);useEffect(() => {const fetchActions = async () => {const promises = apiUrls.map(url => Action.fetch(url).catch(() => null));const actions = await Promise.all(promises);setActions(actions.filter(Boolean) as Action[]);}fetchActions();}, [apiUrls]);useEffect(() => {actions.forEach((action) => action.setAdapter(adapter));}, [actions, adapter]);return actions.map(action => (<div key={action.url} className=flex gap-2><Blink action={action} websiteText={new URL(action.url).hostname} /></div>);}"
] |
Getting started | Actions & Alerts | Getting started
To learn how to setup notifications, see the Notifications Quick Start Guide.
For a more in-depth guide to notifications for your dapp see the Notifications section. Or for a run through on how to send and receive messages with Dialect, which powers notifications under the hood, see the Messaging section.
Previous
Alerts
Next
Alerts Quick Start
Last updated 4 months ago | https://docs.dialect.to/documentation/alerts/getting-started | null |
Alerts & Monitoring | Actions & Alerts | Alerts & Monitoring
This section describes how to set up notifications for your dapp. The end-user experience is the ability for your user's to subscribe to receive timely notifications from your dapp over the channels they care about — SMS, telegram, email, and Dialect inboxes. Flexible tooling allows dapp developers to configure which channels are available, as well as which notification types users can subscribe to — be it NFT buyout requests, liquidation warnings, filled orders, DAO proposal updates, new raffle listings, social posts, etc.
Dialect uses its messaging primitives under the hood to power notifications. In the same way that a business manages an email address to send notifications and other messages to its customers, a dapp manages a wallet keypair for performing messaging with the Dialect protocol (if you're curious how messaging works with Dialect, see the Messaging section).
The rest of this section will abstract away messaging, and focus on the tools used for configuring notifications — from registering a dapp, deciding how to monitor for on- or off-chain events, configuring both the Dialect protocol and traditional web2 channels for sending notifications, to dropping in React components that let your users manage their notifications from your dapp.
Previous
Alerts Quick Start
Next
Registering Your Dapp
Last updated 3 months ago | https://docs.dialect.to/documentation/alerts/alerts-and-monitoring | null |
Decide How to Monitor Events | Actions & Alerts | Decide How to Monitor Events
Notifications can be triggered from a wide range of user behaviors and/or programmatic events. For example: NFT buyout requests, liquidation warnings, filled orders, new DAO proposals, new raffle listings, new social posts, etc.
Option 1: Use Dialect's Open Source Monitoring Tooling
Dialect provides open-source, customizable monitor tooling and service infrastructure to help detect on-chain and/or off-chain events that you would like to notify subscribers about.
Option 2: Use Dialect's Open Source SDK to send Notifications From Your Existing Services
If you already have existing event detection in your own backend service, just jump straight to this section to learn how to send notifications from within your existing service:
Using Your Existing Event Detection
Otherwise, continue forward to learn how to use the Dialect Monitor tooling to detect events and programmatically fire notifications.
Previous
Registering Your Dapp
Next
Using Dialect Monitor to Detect Events
Last updated 3 months ago | https://docs.dialect.to/documentation/alerts/alerts-and-monitoring/decide-how-to-monitor-events | null |
Registering Your Dapp | Actions & Alerts | Registering Your Dapp
To get started, you must first register your dapp within the Dialect Cloud. Analogous to how businesses/users may register for web2 services via an email address, Dialect Cloud uses wallet authentication to register and manage dapps that use Dialect services.
Create a keypair for your dapp
Creating a keypair is analagous to creating a username & password. It is important to first do your own research on how to securely create and manage a keypair, as it will be used to access/administrate your Dialect Cloud account.
First, you must create a keypair and register the corresponding publickey with the Dialect Cloud. We recommend using the Solana CLI to create a new keypair.
Copy
solana-keygen new -o <insert-dapp-name>-messaging-keypair-devnet.json
solana-keygen publickey <insert-dapp-name>-messaging-keypair-devnet.json > dapp-pubkey.pub
This corresponding publickey is analagous to your dapp's "account" identity, and the keypair can be used to sign transactions to authenticate permissioned actions within Dialect Cloud.
Register your dapp in Dialect Cloud
Create an sdk instance following these instructions from . Then register a new dapp messaging keypair for this keypair using the Dialect SDK snippet below.
Dialect's database never stores your dapp's private keys, only the public key.
Copy
// N.b. this created dapp is associated with the wallet public key connected
// to the sdk instance.
const dapp = await sdk.dapps.create({
name: 'My test dapp',
description: `My test dapp's description.`,
blockchainType: BlockchainType.SOLANA
});
Previous
Alerts & Monitoring
Next
Decide How to Monitor Events
Last updated 3 months ago | https://docs.dialect.to/documentation/alerts/alerts-and-monitoring/registering-your-dapp | [
"const dapp = await sdk.dapps.create({name: 'My test dapp',description: `My test dapp's description.`,blockchainType: BlockchainType.SOLANA});"
] |
Using Dialect Monitor to Detect Events | Actions & Alerts | Using Dialect Monitor to Detect Events
Option 1: Use Dialect's Open Source Monitoring Tooling
Dialect has sophisticated, open-source tools for detecting events about changes to data (on- or off-chain) and turning those events into notification messages.
The first piece of this tooling is the Monitor library, an open-source Typescript package that makes it easy to extract and transform data streams into targeted, timely smart messages.
The monitor library provides a rich, high-level API for unbounded data-stream processing to analyze extracted on-chain data or data from other off-chain services.
Data-stream processing features include:
Windowing: fixed size, fixed time, fixed size sliding
Aggregation: average, min, max
Thresholding: rising edge, falling edge
Rate limiting
The Monitor library is best learned by examples. This section describes how to use Dialect monitor to build monitoring apps by showing you various example apps in the examples/ folder of the repository. Follow along in this section, and refer to the code in those examples.
Dapp developer's integrating Dialect notifications should first familiarize themselves with the Monitor library, and then decide which strategies can be used for your use-cases. Alternatively, it may also be helpful to dive straight into an existing open-source implementation detailed in this section, especially if a use-case similar to yours has already been demonstrated.
Once you have completed these sections and implemented the Monitor for your use-case, don't forget to visit this section to view Dialect's Monitor Service hosting recommendations.
We hope you find these sections useful, and would love your contributions to the Monitor library as you may choose to add custom features for your specific use-cases.
Previous
Decide How to Monitor Events
Next
Learning to Use Monitor Builder: Example 1
Last updated 3 months ago | https://docs.dialect.to/documentation/alerts/alerts-and-monitoring/decide-how-to-monitor-events/using-dialect-monitor-to-detect-events | null |
Learning to Use Monitor Builder: Supplying Data | Actions & Alerts | Learning to Use Monitor Builder: Supplying Data
A poll type data source is shown below. Within this poll you would likely perform some custom on- or off-chain data collection. Poll duration is also configured.
Copy
.poll((subscribers: ResourceId[]) => {
const sourceData: SourceData<YourDataType>[] = subscribers.map(
(resourceId) => ({
data: {
cratio: Math.random(),
healthRatio: Math.random(),
resourceId,
},
groupingKey: resourceId.toString(),
}),
);
return Promise.resolve(sourceData);
}, Duration.fromObject({ seconds: 3 }))
A push type data source is describer in this example.
Previous
Learning to Use Monitor Builder: Builder and Data Type
Next
Learning to Use Monitor Builder: Data Transformation
Last updated 1 year ago | https://docs.dialect.to/documentation/alerts/alerts-and-monitoring/decide-how-to-monitor-events/using-dialect-monitor-to-detect-events/learning-to-use-monitor-builder-supplying-data | [
" .poll((subscribers: ResourceId[]) => {const sourceData: SourceData<YourDataType>[] = subscribers.map((resourceId) => ({data: {cratio: Math.random(),healthRatio: Math.random(),resourceId,},groupingKey: resourceId.toString(),}),);return Promise.resolve(sourceData);}, Duration.fromObject({ seconds: 3 }))"
] |
Learning to Use Monitor Builder: Builder and Data Type | Actions & Alerts | Learning to Use Monitor Builder: Builder and Data Type
Monitor.builder (source
Copy
// Dialect SDK is configured and must be supplied
// below in builder props
const environment: DialectCloudEnvironment = 'development';
const dialectSolanaSdk: DialectSdk<Solana> = Dialect.sdk(
{
environment,
},
SolanaSdkFactory.create({
// IMPORTANT: must set environment variable DIALECT_SDK_CREDENTIALS
// to your dapp's Solana messaging wallet keypair e.g. [170,23, . . . ,300]
wallet: NodeDialectSolanaWalletAdapter.create(),
}),
);
// Define a data type to monitor
type YourDataType = {
cratio: number;
healthRatio: number;
resourceId: ResourceId;
};
// Build a Monitor to detect and deliver notifications
const monitor: Monitor<YourDataType> = Monitors.builder({
sdk: dialectSolanaSdk,
subscribersCacheTTL: Duration.fromObject({ seconds: 5 }),
})
// Configure data source type
.defineDataSource<YourDataType>()
Previous
Learning to Use Monitor Builder: Example 1
Next
Learning to Use Monitor Builder: Supplying Data
Last updated 1 year ago | https://docs.dialect.to/documentation/alerts/alerts-and-monitoring/decide-how-to-monitor-events/using-dialect-monitor-to-detect-events/learning-to-use-monitor-builder-builder-and-data-type | [
"const environment: DialectCloudEnvironment = 'development';const dialectSolanaSdk: DialectSdk<Solana> = Dialect.sdk({environment,},SolanaSdkFactory.create({wallet: NodeDialectSolanaWalletAdapter.create(),}),);type YourDataType = {cratio: number;healthRatio: number;resourceId: ResourceId;};const monitor: Monitor<YourDataType> = Monitors.builder({sdk: dialectSolanaSdk,subscribersCacheTTL: Duration.fromObject({ seconds: 5 }),}).defineDataSource<YourDataType>()"
] |
Learning to Use Monitor Builder: Data Transformation | Actions & Alerts | Learning to Use Monitor Builder: Data Transformation
During the transform step, streaming data from the previous step (eg poll, push) is operated on in succession to identify some event and trigger actions. In this snippet, a falling-edge of 0.5 on a number data type.
Copy
.transform<number, number>({
keys: ['cratio'],
pipelines: [
Pipelines.threshold({
type: 'falling-edge',
threshold: 0.5,
}),
],
})
Many other data-stream processing features exist, including:
Windowing: fixed size, fixed time, fixed size sliding
Aggregation: average, min, max
Thresholding: rising edge, falling edge
More Examples:
monitor/005-custom-pipelines-using-operators.ts at main · dialectlabs/monitor
GitHub
Custom Pipeline Operators Examples
monitor/008-diff-pipeline.ts at main · dialectlabs/monitor
GitHub
Array Diff
An array diff pipeline can be used to track when items are added or removed from an array.
Previous
Learning to Use Monitor Builder: Supplying Data
Next
Learning to Use Monitor Builder: Notify Step
Last updated 1 year ago | https://docs.dialect.to/documentation/alerts/alerts-and-monitoring/decide-how-to-monitor-events/using-dialect-monitor-to-detect-events/learning-to-use-monitor-builder-data-transformation | null |
Learning to Use Monitor Builder: Example 1 | Actions & Alerts | Learning to Use Monitor Builder: Example 1
This example emulates e2e scenario for monitoring some on- or off-chain resources for a set of subscribers and has 2 parts:
Client that emulates several users subscribing for dialect notifications from a monitoring service
Server that monitors some data for a set of monitoring service subscribers
This example follows the code at examples/000.1-solana-monitoring-service.ts
Server example:
Copy
import { Monitor, Monitors, Pipelines, ResourceId, SourceData } from '../src';
import { Duration } from 'luxon';
// 1. Common Dialect SDK imports
import {
Dialect,
DialectCloudEnvironment,
DialectSdk,
} from '@dialectlabs/sdk';
// 2. Solana-specific imports
import {
Solana,
SolanaSdkFactory,
NodeDialectSolanaWalletAdapter
} from '@dialectlabs/blockchain-sdk-solana';
// 3. Create Dialect Solana SDK
const environment: DialectCloudEnvironment = 'development';
const dialectSolanaSdk: DialectSdk<Solana> = Dialect.sdk(
{
environment,
},
SolanaSdkFactory.create({
// IMPORTANT: must set environment variable DIALECT_SDK_CREDENTIALS
// to your dapp's Solana messaging wallet keypair e.g. [170,23, . . . ,300]
wallet: NodeDialectSolanaWalletAdapter.create(),
}),
);
// 4. Define a data type to monitor
type YourDataType = {
cratio: number;
healthRatio: number;
resourceId: ResourceId;
};
// 5. Build a Monitor to detect and deliver notifications
const dataSourceMonitor: Monitor<YourDataType> = Monitors.builder({
sdk: dialectSolanaSdk,
subscribersCacheTTL: Duration.fromObject({ seconds: 5 }),
})
// (5a) Define data source type
.defineDataSource<YourDataType>()
// (5b) Supply data to monitor, in this case by polling
// Push type available, see example 007
.poll((subscribers: ResourceId[]) => {
const sourceData: SourceData<YourDataType>[] = subscribers.map(
(resourceId) => ({
data: {
cratio: Math.random(),
healthRatio: Math.random(),
resourceId,
},
groupingKey: resourceId.toString(),
}),
);
return Promise.resolve(sourceData);
}, Duration.fromObject({ seconds: 3 }))
// (5c) Transform data source to detect events
.transform<number, number>({
keys: ['cratio'],
pipelines: [
Pipelines.threshold({
type: 'falling-edge',
threshold: 0.5,
}),
],
})
// (5d) Add notification sinks for message delivery strategy
// Monitor has several sink types available out-of-the-box.
// You can also define your own sinks to deliver over custom channels
// (see examples/004-custom-notification-sink)
// Below, the dialectSdk sync is used, which handles logic to send
// notifications to all all (and only) the channels which has subscribers have enabled
.notify()
.dialectSdk(
({ value }) => {
return {
title: 'dApp cratio warning',
message: `Your cratio = ${value} below warning threshold`,
};
},
{
dispatch: 'unicast',
to: ({ origin: { resourceId } }) => resourceId,
},
)
.also()
.transform<number, number>({
keys: ['cratio'],
pipelines: [
Pipelines.threshold({
type: 'rising-edge',
threshold: 0.5,
}),
],
})
.notify()
.dialectSdk(
({ value }) => {
return {
title: 'dApp cratio warning',
message: `Your cratio = ${value} above warning threshold`,
};
},
{
dispatch: 'unicast',
to: ({ origin: { resourceId } }) => resourceId,
},
)
// (5e) Build the Monitor
.and()
.build();
// 6. Start the monitor
dataSourceMonitor.start();
Please follow the instructions below to run the example
Step 1. Generate a new test keypair representing your dapp's monitoring service
Copy
export your_path=~/projects/dialect/keypairs/
solana-keygen new --outfile ${your_path}/monitor-localnet-keypair.private
solana-keygen pubkey ${your_path}/monitor-localnet-keypair.private > ${your_path}/monitor-localnet-keypair.public
Step 2. Start server with keypair assigned to env DIALECT_SDK_CREDENTIALS
Copy
cd examples
export your_path=~/projects/dialect/keypairs
DIALECT_SDK_CREDENTIALS=$(cat ${your_path}/monitor-localnet-keypair.private) ts-node ./000.1-solana-monitoring-service-server.ts
Step 3. Start client
Copy
cd examples
export your_path=~/projects/dialect/keypairs
DAPP_PUBLIC_KEY=$(cat ${your_path}/monitor-localnet-keypair.public) \
ts-node ./000.1-solana-monitoring-service-client.ts
Step 4. Look at client logs for notifications
When both client and server are started, server will start polling data and notifying subscribers
Previous
Using Dialect Monitor to Detect Events
Next
Learning to Use Monitor Builder: Builder and Data Type
Last updated 1 year ago | https://docs.dialect.to/documentation/alerts/alerts-and-monitoring/decide-how-to-monitor-events/using-dialect-monitor-to-detect-events/learning-to-use-monitor-builder-example-1 | [
"import { Monitor, Monitors, Pipelines, ResourceId, SourceData } from '../src';import { Duration } from 'luxon';import {Dialect,DialectCloudEnvironment,DialectSdk,} from '@dialectlabs/sdk';import {Solana,SolanaSdkFactory,NodeDialectSolanaWalletAdapter} from '@dialectlabs/blockchain-sdk-solana';const environment: DialectCloudEnvironment = 'development';const dialectSolanaSdk: DialectSdk<Solana> = Dialect.sdk({environment,},SolanaSdkFactory.create({wallet: NodeDialectSolanaWalletAdapter.create(),}),);type YourDataType = {cratio: number;healthRatio: number;resourceId: ResourceId;};const dataSourceMonitor: Monitor<YourDataType> = Monitors.builder({sdk: dialectSolanaSdk,subscribersCacheTTL: Duration.fromObject({ seconds: 5 }),}).defineDataSource<YourDataType>().poll((subscribers: ResourceId[]) => {const sourceData: SourceData<YourDataType>[] = subscribers.map((resourceId) => ({data: {cratio: Math.random(),healthRatio: Math.random(),resourceId,},groupingKey: resourceId.toString(),}),);return Promise.resolve(sourceData);}, Duration.fromObject({ seconds: 3 })).transform<number, number>({keys: ['cratio'],pipelines: [Pipelines.threshold({type: 'falling-edge',threshold: 0.5,}),],}).notify().dialectSdk(({ value }) => {return {title: 'dApp cratio warning',message: `Your cratio = ${value} below warning threshold`,};},{dispatch: 'unicast',to: ({ origin: { resourceId } }) => resourceId,},).also().transform<number, number>({keys: ['cratio'],pipelines: [Pipelines.threshold({type: 'rising-edge',threshold: 0.5,}),],}).notify().dialectSdk(({ value }) => {return {title: 'dApp cratio warning',message: `Your cratio = ${value} above warning threshold`,};},{dispatch: 'unicast',to: ({ origin: { resourceId } }) => resourceId,},).and().build();dataSourceMonitor.start();",
"export your_path=~/projects/dialect/keypairs/solana-keygen new --outfile ${your_path}/monitor-localnet-keypair.privatesolana-keygen pubkey ${your_path}/monitor-localnet-keypair.private > ${your_path}/monitor-localnet-keypair.public",
"cd examplesexport your_path=~/projects/dialect/keypairsDIALECT_SDK_CREDENTIALS=$(cat ${your_path}/monitor-localnet-keypair.private) ts-node ./000.1-solana-monitoring-service-server.ts",
"cd examplesexport your_path=~/projects/dialect/keypairsDAPP_PUBLIC_KEY=$(cat ${your_path}/monitor-localnet-keypair.public) \ts-node ./000.1-solana-monitoring-service-client.ts"
] |
Learning to Use Monitor Builder: Notify Step | Actions & Alerts | Learning to Use Monitor Builder: Notify Step
The dialectSdk notification sink is the standard notification sink. This data sink allows to unicast, multicast, or broadcast a message. Under the hood the SDK handles delivering the notification to any-and-all notification channels that the subscriber(s) has enabled.
Copy
.notify()
.dialectSdk(
({ value }) => {
return {
title: 'dApp cratio warning',
message: `Your cratio = ${value} below warning threshold`,
};
},
{
dispatch: 'unicast',
to: ({ origin: { resourceId } }) => resourceId,
},
)
Custom sinks can be added as show in this example.
Previous
Learning to Use Monitor Builder: Data Transformation
Next
Monitor Hosting Options
Last updated 1 year ago | https://docs.dialect.to/documentation/alerts/alerts-and-monitoring/decide-how-to-monitor-events/using-dialect-monitor-to-detect-events/learning-to-use-monitor-builder-notify-step | [
" .notify().dialectSdk(({ value }) => {return {title: 'dApp cratio warning',message: `Your cratio = ${value} below warning threshold`,};},{dispatch: 'unicast',to: ({ origin: { resourceId } }) => resourceId,},)"
] |
Monitor Hosting Options | Actions & Alerts | Monitor Hosting Options
Now that you have learned to implement a Dialect Monitor to detect and programmatically send notifications to your subscribers, you will need to host that monitor within a service.
If you already have a preferred infrastructure/framework for hosting services, you can simply choose to host and manage your Monitor that way, and you can skip directly to this section to setup your UI/UX experience for users:
Advancing React Notifications
Otherwise, Dialect offers an opinionated/standardized way of hosting a Monitor within a Dialect Monitoring Service (Nest.js server implementation).
If you would like to use this opinionated hosting option, continue forward.
Previous
Learning to Use Monitor Builder: Notify Step
Next
Using Dialect Monitoring Service
Last updated 1 year ago | https://docs.dialect.to/documentation/alerts/alerts-and-monitoring/decide-how-to-monitor-events/using-dialect-monitor-to-detect-events/monitor-hosting-options | null |
Using Your Existing Event Detection | Actions & Alerts | Using Your Existing Event Detection
Option 2: Use Dialect's Open Source SDK to send Notifications From Your Existing Services
If you already have off-chain services that are detecting the events you care about, you can easily import the Dialect SDK into those services to send notifications to subscribers right as those events are detected.
The following sections will walk through importing the SDK into your application and sending notifications.
Previous
Using Dialect Monitoring Service
Next
Use Dialect SDK to Send Notifications
Last updated 3 months ago | https://docs.dialect.to/documentation/alerts/alerts-and-monitoring/decide-how-to-monitor-events/using-your-existing-event-detection | null |
Using Dialect Monitoring Service | Actions & Alerts | Using Dialect Monitoring Service
Dialect Reference Implementation
To wrap your Monitor within a monitoring service, see Dialect's default reference implementation at:
https://github.com/dialectlabs/monitoring-service-template
github.com
Monitoring Service Template Repository
Open Source Implementations of the Monitoring Service
It could also be useful to explore some real, open-source partner implementations. See if any of these repositories have use-cases similar to yours.
Not all of these implementations are using the latest version of Dialect packages. It is highly recommended that you use these to examples to learn from, but implement yours with all latest Dialect package dependencies to take advantage of new features and bug fixes.
Governance / DAO
DeFi
Next Steps
Now that you have built and are hosting a monitoring service, you can jump straight to setting up your Notifications UI/UX:
Advancing React Notifications
Previous
Monitor Hosting Options
Next
Using Your Existing Event Detection
Last updated 1 year ago | https://docs.dialect.to/documentation/alerts/alerts-and-monitoring/decide-how-to-monitor-events/using-dialect-monitor-to-detect-events/using-dialect-monitoring-service | null |
Use Dialect SDK to Send Notifications | Actions & Alerts | Use Dialect SDK to Send Notifications
Using the Dialect SDK to send notifications from within your backend services is essentially a two-step process:
Load your dapp from a Dialect SDK instance using your dapp's DIALECT_SDK_CREDENTIALS and configuration parameters.
Send dialect notifications at the place of event in your application.
It is up to you how to optimize your backend and integrate these two steps to send timely notifications to your users. Of course, if you end up finding that your existing service are not well suited for event monitoring and notification delivery, you can explore using the Dialect Monitor to build a custom on- or off-chain monitoring service.
These sections in the SDK portion of documentation detail this easy two-step process:
Load your dapp
Sending Dapp-to-User Messages
Here is an example of a live integration of the Dialect SDK into the governance-api backend. This integration is used power notifications for post/comment upvotes & replies on the Realms Discover dapp. The Dialect SDK is setup here (in this case, wrapped within NestJs to match their architecture), and an example of firing a notification from within their existing services occurs here.
Now that you have setup notifications in your backend, you are ready to set up your Notifications UI/UX.
Previous
Using Your Existing Event Detection
Next
Advancing React Notifications
Last updated 3 months ago | https://docs.dialect.to/documentation/alerts/alerts-and-monitoring/decide-how-to-monitor-events/using-your-existing-event-detection/use-dialect-sdk-to-send-notifications | null |
Advancing React Notifications | Actions & Alerts | Advancing React Notifications
Try a live example of the Dialect notification bell at https://alerts-example.dialect.to.
Previous
Use Dialect SDK to Send Notifications
Next
Using development environment
Last updated 3 months ago | https://docs.dialect.to/documentation/alerts/alerts-and-monitoring/advancing-react-notifications | null |
Using development environment | Actions & Alerts | Using development environment
We provide a free to use development environment to test your notifications. Here's example how to configure development environment:
Copy
'use client';
import '@dialectlabs/react-ui/index.css';
import { DialectSolanaSdk } from '@dialectlabs/react-sdk-blockchain-solana';
import {
Icons,
NotificationTypeStyles,
NotificationsButton,
} from '@dialectlabs/react-ui';
const DAPP_ADDRESS = '...';
export const DialectSolanaNotificationsButton = () => {
return (
<DialectSolanaSdk
dappAddress={DAPP_ADDRESS}
/* pass config property with environment set to development */
/* by default it'll use production environment */
config={{
environment: 'development',
}}
>
<NotificationsButton />
</DialectSolanaSdk>
);
};
Previous
Advancing React Notifications
Next
Styling Notifications widget
Last updated 3 months ago | https://docs.dialect.to/documentation/alerts/alerts-and-monitoring/advancing-react-notifications/using-development-environment | [
"'use client';import '@dialectlabs/react-ui/index.css';import { DialectSolanaSdk } from '@dialectlabs/react-sdk-blockchain-solana';import {Icons,NotificationTypeStyles,NotificationsButton,} from '@dialectlabs/react-ui';const DAPP_ADDRESS = '...';export const DialectSolanaNotificationsButton = () => {return (<DialectSolanaSdkdappAddress={DAPP_ADDRESS}config={{environment: 'development',}}><NotificationsButton /></DialectSolanaSdk>);};"
] |
Overriding icons | Actions & Alerts | Overriding icons
You can override icons according to your icons set in the app. Here's an example how to render a custom react component instead of built in icons:
Copy
// DialectNotificationComponent.tsx
'use client';
import '@dialectlabs/react-ui/index.css';
import { SVGProps } from 'react';
import { DialectSolanaSdk } from '@dialectlabs/react-sdk-blockchain-solana';
import {
Icons,
NotificationTypeStyles,
NotificationsButton,
} from '@dialectlabs/react-ui';
const DAPP_ADDRESS = '...';
// Override a set of icons in the Icons variable before using dialect component
Icons.Close = (props: SVGProps<SVGSVGElement>) => {
// render your close icon instead of the default one
return null;
}
export const DialectSolanaNotificationsButton = () => {
return (
<DialectSolanaSdk dappAddress={DAPP_ADDRESS}>
<NotificationsButton />
</DialectSolanaSdk>
);
};
Here's the full list of built in icons:
Copy
export const Icons = {
Loader: SpinnerDots,
Settings: SettingsIcon,
ArrowLeft: ArrowLeftIcon,
ArrowRight: ArrowRightIcon,
Close: CloseIcon,
Bell: BellIcon,
BellButton: BellButtonIcon,
BellButtonOutline: BellButtonIconOutline,
Trash: TrashIcon,
Xmark: XmarkIcon,
Resend: ResendIcon,
Wallet: WalletIcon,
};
Previous
Styling Notifications widget
Next
Styling different notification types
Last updated 3 months ago | https://docs.dialect.to/documentation/alerts/alerts-and-monitoring/advancing-react-notifications/overriding-icons | [
"'use client';import '@dialectlabs/react-ui/index.css';import { SVGProps } from 'react';import { DialectSolanaSdk } from '@dialectlabs/react-sdk-blockchain-solana';import {Icons,NotificationTypeStyles,NotificationsButton,} from '@dialectlabs/react-ui';const DAPP_ADDRESS = '...';Icons.Close = (props: SVGProps<SVGSVGElement>) => {return null;}export const DialectSolanaNotificationsButton = () => {return (<DialectSolanaSdk dappAddress={DAPP_ADDRESS}><NotificationsButton /></DialectSolanaSdk>);};"
] |
Customizing notifications channels | Actions & Alerts | Customizing notifications channels
Currently we support the following notifications channels:
wallet
telegram
email
By default all channels are enabled, but you can pass a set of different channels:
Copy
'use client';
import '@dialectlabs/react-ui/index.css';
import { DialectSolanaSdk } from '@dialectlabs/react-sdk-blockchain-solana';
import {
Icons,
NotificationTypeStyles,
NotificationsButton,
} from '@dialectlabs/react-ui';
const DAPP_ADDRESS = '...';
export const DialectSolanaNotificationsButton = () => {
return (
<DialectSolanaSdk dappAddress={DAPP_ADDRESS}>
/* enables wallet channel only */
<NotificationsButton channels={['wallet']} />
</DialectSolanaSdk>
);
};
Previous
Styling different notification types
Next
Customizing notifications button
Last updated 3 months ago | https://docs.dialect.to/documentation/alerts/alerts-and-monitoring/advancing-react-notifications/customizing-notifications-channels | [
"'use client';import '@dialectlabs/react-ui/index.css';import { DialectSolanaSdk } from '@dialectlabs/react-sdk-blockchain-solana';import {Icons,NotificationTypeStyles,NotificationsButton,} from '@dialectlabs/react-ui';const DAPP_ADDRESS = '...';export const DialectSolanaNotificationsButton = () => {return (<DialectSolanaSdk dappAddress={DAPP_ADDRESS}><NotificationsButton channels={['wallet']} /></DialectSolanaSdk>);};"
] |
Styling different notification types | Actions & Alerts | Styling different notification types
You'll probably have a multiple notification types for your app. By default all notifications are rendered with the same bell icon.
Default notification rendering
You can customize icon depending on notification types. For example you might want to have a green checkmark if notification is 'positive' for user, or add a red cross if notification is 'negative' for user.
customizing a notification icon
See how to manage your notification types:
Managing notification types
Here's an example how to achieve it:
Copy
'use client';
import '@dialectlabs/react-ui/index.css';
import { DialectSolanaSdk } from '@dialectlabs/react-sdk-blockchain-solana';
import {
Icons,
NotificationTypeStyles,
NotificationsButton,
} from '@dialectlabs/react-ui';
const DAPP_ADDRESS = '...';
// assume that you created notification type with human readable id 'fav_nft_listed'
// You can add as many entries to NotificationTypeStyles
NotificationTypeStyles.fav_nft_listed = {
Icon: <Icons.Bell width={12} height={12} />, // custom react component to render icon
iconColor: '#FFFFFF',
iconBackgroundColor: '#FF0000',
iconBackgroundBackdropColor: '#FF00001A',
linkColor: '#FF0000', // notifications might contain CTA link, you can customize color
};
export const DialectSolanaNotificationsButton = () => {
return (
<DialectSolanaSdk dappAddress={DAPP_ADDRESS}>
<NotificationsButton />
</DialectSolanaSdk>
);
};
Previous
Overriding icons
Next
Customizing notifications channels
Last updated 3 months ago | https://docs.dialect.to/documentation/alerts/alerts-and-monitoring/advancing-react-notifications/styling-different-notification-types | null |
Customizing notifications button | Actions & Alerts | Customizing notifications button
In some cases you might want to use your custom button component.
NotificationButton component can accept a function as a children with the following properties:
open - boolean value indicating if dialect modal is open
setOpen - react callback to control dialect modal open state
unreadCount - number of unread notifications in case if you want to render unread notifications badge
ref - react ref callback to your component under the hood. You must pass ref to your button.
Here's example of passing a custom component instead of built-in button:
Copy
'use client';
import '@dialectlabs/react-ui/index.css';
import { DialectSolanaSdk } from '@dialectlabs/react-sdk-blockchain-solana';
import {
Icons,
NotificationTypeStyles,
NotificationsButton,
} from '@dialectlabs/react-ui';
const DAPP_ADDRESS = '...';
export const DialectSolanaNotificationsButton = () => {
return (
<DialectSolanaSdk dappAddress={DAPP_ADDRESS}>
<NotificationsButton>
{({ open, setOpen, unreadCount, ref }) => {
return (
<button ref={ref} onClick={() => setOpen((prev) => !prev)}>
my cool button
</button>
);
}}
</NotificationsButton>
</DialectSolanaSdk>
);
};
Previous
Customizing notifications channels
Next
Using your own modal component
Last updated 3 months ago | https://docs.dialect.to/documentation/alerts/alerts-and-monitoring/advancing-react-notifications/customizing-notifications-button | null |
Using your own modal component | Actions & Alerts | Using your own modal component
In some rare cases you might want to highly customize modal window. The easiest way is to use your own component.
NotificationButton component can accept a react component reference renderModalComponent with the following arguments:
open - boolean value indicating if dialect modal is open
setOpen - react callback to control dialect modal open state
children - children components that your modal component should render. You must render children.
ref - react ref callback to your component under the hood. You must pass reference.
Copy
'use client';
import '@dialectlabs/react-ui/index.css';
import { DialectSolanaSdk } from '@dialectlabs/react-sdk-blockchain-solana';
import {
Icons,
NotificationTypeStyles,
NotificationsButton,
} from '@dialectlabs/react-ui';
const DAPP_ADDRESS = '...';
export const DialectSolanaNotificationsButton = () => {
return (
<DialectSolanaSdk dappAddress={DAPP_ADDRESS}>
<NotificationsButton
renderModalComponent={({ open, setOpen, ref, children }) => {
if (!open) {
return null;
}
return (
<div ref={ref} className="fixed inset-0 z-10">
{children}
</div>
);
}}
/>
</DialectSolanaSdk>
);
};
Previous
Customizing notifications button
Next
Using standalone notifications component
Last updated 3 months ago | https://docs.dialect.to/documentation/alerts/alerts-and-monitoring/advancing-react-notifications/using-your-own-modal-component | [
"'use client';import '@dialectlabs/react-ui/index.css';import { DialectSolanaSdk } from '@dialectlabs/react-sdk-blockchain-solana';import {Icons,NotificationTypeStyles,NotificationsButton,} from '@dialectlabs/react-ui';const DAPP_ADDRESS = '...';export const DialectSolanaNotificationsButton = () => {return (<DialectSolanaSdk dappAddress={DAPP_ADDRESS}><NotificationsButtonrenderModalComponent={({ open, setOpen, ref, children }) => {if (!open) {return null;}return (<div ref={ref} className=fixed inset-0 z-10>{children}</div>);}}/></DialectSolanaSdk>);};"
] |
Styling Notifications widget | Actions & Alerts | Styling Notifications widget
You can style the following entities of the notifications component:
colors
border radius
font
modal container
Styling colors
Dialect defines a set of css variables, which are used to color the whole widget:
Copy
.dialect {
--dt-accent-brand: #09cbbf;
--dt-accent-error: #f62d2d;
--dt-bg-brand: #ebebeb;
--dt-bg-primary: #ffffff;
--dt-bg-secondary: #f9f9f9;
--dt-bg-tertiary: #f2f3f5;
--dt-brand-transparent: #b3b3b31a;
--dt-button-primary: #2a2a2b;
--dt-button-primary-disabled: #656564;
--dt-button-primary-hover: #434445;
--dt-button-secondary: #ebebeb;
--dt-button-secondary-disabled: #f2f3f5;
--dt-button-secondary-hover: #f2f3f5;
--dt-icon-primary: #2a2a2b;
--dt-icon-secondary: #888989;
--dt-icon-tertiary: #b3b3b3;
--dt-input-checked: #09cbbf;
--dt-input-primary: #dee1e7;
--dt-input-secondary: #ffffff;
--dt-input-unchecked: #d7d7d7;
--dt-stroke-primary: #dee1e7;
--dt-text-accent: #08c0b4;
--dt-text-inverse: #ffffff;
--dt-text-primary: #232324;
--dt-text-quaternary: #888989;
--dt-text-secondary: #434445;
--dt-text-tertiary: #737373;
}
You can override this variables just as any other css variables and specify any other color, or you can reference any other variable in your existing styles, like this:
Copy
.dialect {
--dt-bg-primary: #ff00ff; /* make sure your css is imported after the dialect styles */
--dt-bg-secondary: #ff00ff !important; /* You might want to add !important tag to avoid css import ordering issue */
--dt-bg-tertiary: var(--my-cool-background); /* You can reference you css variable to avoid copy/paste and handle light/dark theme for example */
}
As an option, you can include dialect styles before your styles by importing it directly in your css file:
Copy
@import url('@dialectlabs/react-ui/index.css');
Use the following visual guide to style widget. Please note that css variables are prefixed with --dt
Available tokens
Settings screen styling guide
Buttons states
Text fields states
Notification connect wallet screen styling guide
Notification feed styling guide
See Styling different notification types to learn how to style icons/links colors in notifications feed.
Force dark theme
You can force dark theme for dialect component. For this you can pass theme='dark' prop to dialect components.
Copy
export const DialectSolanaNotificationsButton = () => {
return (
<DialectSolanaSdk dappAddress={DAPP_ADDRESS}>
<NotificationsButton theme="dark" />
</DialectSolanaSdk>
);
};
This would apply a built in dark theme variables:
Copy
.dialect[data-theme='dark'] {
--dt-accent-brand: #09cbbf;
--dt-accent-error: #ff4747;
--dt-bg-brand: #656564;
--dt-bg-primary: #1b1b1c;
--dt-bg-secondary: #232324;
--dt-bg-tertiary: #2a2a2b;
--dt-brand-transparent: #b3b3b31a;
--dt-button-primary: #ffffff;
--dt-button-primary-disabled: #dee1e7;
--dt-button-primary-hover: #f9f9f9;
--dt-button-secondary: #323335;
--dt-button-secondary-disabled: #434445;
--dt-button-secondary-hover: #383a3c;
--dt-icon-primary: #ffffff;
--dt-icon-secondary: #888989;
--dt-icon-tertiary: #737373;
--dt-input-checked: #09cbbf;
--dt-input-primary: #434445;
--dt-input-secondary: #1b1b1c;
--dt-input-unchecked: #656564;
--dt-stroke-primary: #323335;
--dt-text-accent: #09cbbf;
--dt-text-inverse: #1b1b1c;
--dt-text-primary: #ffffff;
--dt-text-quaternary: #888989;
--dt-text-secondary: #c4c6c8;
--dt-text-tertiary: #888989;
}
Styling border radius
Dialect defines a set of css variables, which are used to configure border radiuses for the widget:
Copy
.dialect {
--dt-border-radius-xs: 0.375rem;
--dt-border-radius-s: 0.5rem;
--dt-border-radius-m: 0.75rem;
--dt-border-radius-l: 1rem;
}
Styling font
Font should inherit your in-app css font configuration by default. In case if it didn't happened for some reason, you can override it for .dialect css classname.
Styling modal
You can customize .dt-modal css class to change the default modal behavior. Here's the default css styles applied to modal window:
Copy
/* mobile phones */
.dialect .dt-modal {
position: fixed;
right: 0px;
top: 0px;
z-index: 100;
height: 100%;
width: 100%;
}
/* tablet/desktop */
@media (min-width: 640px) {
.dialect .dt-modal {
position: absolute;
top: 4rem;
height: 600px;
width: 420px;
}
}
/* styling */
.dialect .dt-modal {
overflow: hidden;
border-radius: var(--dt-border-radius-l);
border-width: 1px;
border-color: var(--dt-stroke-primary);
}
If you want to bring your own modal container see:
Using your own modal component
Previous
Using development environment
Next
Overriding icons
Last updated 2 months ago | https://docs.dialect.to/documentation/alerts/alerts-and-monitoring/advancing-react-notifications/styling-notifications-widget | null |
Using standalone notifications component | Actions & Alerts | Using standalone notifications component
In some rare cases you might want to just use Notifications component without built-in button and modal window. For example you might want to put component statically to the right side of your page. In this case you bring your own logic to display component and your own modal window. You don't need to use .dt-modal css classname in this case.
Notifications component accepts the following properties:
setOpen - if functions passed, then Notifications component will have a cross in the top right corner
channels - see "Customizing notifications channels" page
Copy
'use client';
import '@dialectlabs/react-ui/index.css';
import { DialectSolanaSdk } from '@dialectlabs/react-sdk-blockchain-solana';
import { Notifications } from '@dialectlabs/react-ui';
const DAPP_ADDRESS = '...';
export const DialectSolanaNotificationsButton = () => {
return (
<DialectSolanaSdk dappAddress={DAPP_ADDRESS}>
<div id="my-container" className="fixed right-0 z-10 w-[500px]">
/* no modal and no button are rendered */
<Notifications />
</div>
</DialectSolanaSdk>
);
};
Previous
Using your own modal component
Next
Using custom wallet adapter
Last updated 3 months ago | https://docs.dialect.to/documentation/alerts/alerts-and-monitoring/advancing-react-notifications/using-standalone-notifications-component | [
"'use client';import '@dialectlabs/react-ui/index.css';import { DialectSolanaSdk } from '@dialectlabs/react-sdk-blockchain-solana';import { Notifications } from '@dialectlabs/react-ui';const DAPP_ADDRESS = '...';export const DialectSolanaNotificationsButton = () => {return (<DialectSolanaSdk dappAddress={DAPP_ADDRESS}><div id=my-container className=fixed right-0 z-10 w-[500px]><Notifications /></div></DialectSolanaSdk>);};"
] |
Using custom wallet adapter | Actions & Alerts | Using custom wallet adapter
In some cases you might want to use a custom wallet adapter instead of @solana/wallet-adapter-react Here's how you can do it:
Copy
'use client';
import '@dialectlabs/react-ui/index.css';
import {
DialectSolanaSdk,
Environment,
} from '@dialectlabs/react-sdk-blockchain-solana';
import {
Icons,
NotificationTypeStyles,
NotificationsButton,
ThemeType,
} from '@dialectlabs/react-ui';
import { useWallet } from '@solana/wallet-adapter-react';
const DAPP_ADDRESS = '...'
export const DialectSolanaNotificationsButton = () => {
const wallet = useWallet(); // as an example we'll use solana wallet adapter
const walletAdapter: DialectSolanaWalletAdapter = useMemo(
() => ({
publicKey: wallet.publicKey, // PublicKey | null
signMessage: wallet.signMessage, // (msg: Uint8Array) => Promise<Uint8Array>
signTransaction: wallet.signTransaction,// <T extends Transaction | VersionedTransaction>(tx: T) => Promise<T>
}),
[wallet],
);
return (
<DialectSolanaSdk
dappAddress={DAPP_ADDRESS}
// if you pass customWalletAdapter property, it'll use it instead of wallet context
customWalletAdapter={walletAdapter}
>
<NotificationsButton theme={props.theme} />
</DialectSolanaSdk>
);
};
Previous
Using standalone notifications component
Next
Broadcast: Building Your Audience
Last updated 3 months ago | https://docs.dialect.to/documentation/alerts/alerts-and-monitoring/advancing-react-notifications/using-custom-wallet-adapter | [
"'use client';import '@dialectlabs/react-ui/index.css';import {DialectSolanaSdk,Environment,} from '@dialectlabs/react-sdk-blockchain-solana';import {Icons,NotificationTypeStyles,NotificationsButton,ThemeType,} from '@dialectlabs/react-ui';import { useWallet } from '@solana/wallet-adapter-react';const DAPP_ADDRESS = '...'export const DialectSolanaNotificationsButton = () => {const wallet = useWallet();const walletAdapter: DialectSolanaWalletAdapter = useMemo(() => ({publicKey: wallet.publicKey, signMessage: wallet.signMessage,signTransaction: wallet.signTransaction,}),[wallet],);return (<DialectSolanaSdkdappAddress={DAPP_ADDRESS}customWalletAdapter={walletAdapter}><NotificationsButton theme={props.theme} /></DialectSolanaSdk>);};"
] |
SDK | Actions & Alerts | SDK
This section describes how to interact with Dialect via an SDK.
Previous
Broadcast: Building Your Audience
Next
Typescript
Last updated 3 months ago | https://docs.dialect.to/documentation/alerts/alerts-and-monitoring/sdk | null |
Installation | Actions & Alerts | Installation
To start sending notifications with Dialect via it's Typescript SDK, first install @dialectlabs/sdk. This is the same installation as Messaging.
npm:
Copy
npm install @dialectlabs/sdk --save
# Solana notifications
npm install @dialectlabs/blockchain-sdk-solana --save
# Aptos notifications
npm install @dialectlabs/blockchain-sdk-aptos --save
yarn:
Copy
yarn add @dialectlabs/sdk
# Solana notifications
yarn add @dialectlabs/blockchain-sdk-solana
# Aptos notifications
yarn add @dialectlabs/blockchain-sdk-aptos
Previous
Typescript
Next
Configuration
Last updated 3 months ago | https://docs.dialect.to/documentation/alerts/alerts-and-monitoring/sdk/typescript/installation | null |
Typescript | Actions & Alerts | Typescript
Installation
Configuration
Managing addresses
Subscribing to notifications
Load your dapp
Sending Dapp-to-User Messages
Managing notification types
Previous
SDK
Next
Installation
Last updated 3 months ago | https://docs.dialect.to/documentation/alerts/alerts-and-monitoring/sdk/typescript | null |
Configuration | Actions & Alerts | Configuration
All interactions with Dialect are done by first creating an sdk client, with some initial configuration. This configuration specifies:
What chains to use, such as Solana or Aptos.
What backends to use, including both the Dialect on chain Solana backend (v0), and/or the free, multi-chain Dialect cloud backend (v1).
What environment to target, including local-development, development, & production.
It is recommended that you perform the following actions targeting the Dialect development environment, and only switch to production when you're ready.
Previous
Installation
Next
Managing addresses
Last updated 3 months ago | https://docs.dialect.to/documentation/alerts/alerts-and-monitoring/sdk/typescript/configuration | null |
Broadcast: Building Your Audience | Actions & Alerts | Broadcast: Building Your Audience
Many dapps wish to send product updates, community announcements, and other manually-crafted notifications to their users. Dialect offers an administrator dashboard for sending these announcements. Dapp administrators can connect to the dashboard here using your dapp's messaging keypair that you created in the Registering Your Dapp section to use these incredible community building features!
Previous
Using custom wallet adapter
Next
SDK
Last updated 3 months ago | https://docs.dialect.to/documentation/alerts/alerts-and-monitoring/broadcast-building-your-audience | null |
Subscribing to notifications | Actions & Alerts | Subscribing to notifications
Dialect allows users to manage subscriptions to receive notifications from dapps to specific addresses they have registered.
Addresses include not just their wallet via the Dialect protocol, but also email, Telegram, & SMS. To learn more about addresses, see the previous section on managing addresses.
A subscription, a linker table between dapps & addresses, is called a dappAddress.This will likely be renamed as it can be misleading.
Create a subscription
A subscription, or dappAddress must first be created.
Copy
// Subscribe to receive dapp notifications to address
const subscription = await sdk.wallet.dappAddresses.create({
addressId: address.id,
enabled: true,
dappPublicKey
})
Enabling & disabling a subscription
Once created, a subscription may be enabled or disabled for a given. Disabling a subscription means no notifications will be sent to that address for that dapp until it is reenabled.t
Copy
// Enable/disable subscription
const updatedSubscription = await sdk.wallet.dappAddresses.update({
dappAddressId: subscription.id,
enabled: false,
});
Getting subscriptions
Find a subscription by its id
Copy
// Find specific address subscription owned by wallet
const specificSubscription = await sdk.wallet.dappAddresses.find({
dappAddressId: subscription.id
});
Find subscriptions by wallet (& optionally filter by dapp)
Copy
// Find all address subscriptions owned by wallet and optionally filtering
// by dapp or address ids.
const allSubscriptions = await sdk.wallet.dappAddresses.findAll({
dappPublicKey, // optional parameter
addressIds: [address.id] // optional parameter
});
Deleting a subscription
Copy
// Delete subscription
await sdk.wallet.dappAddresses.delete({
dappAddressId: subscription.id
})
Previous
Managing addresses
Next
Load your dapp
Last updated 3 months ago | https://docs.dialect.to/documentation/alerts/alerts-and-monitoring/sdk/typescript/subscribing-to-notifications | null |
Managing addresses | Actions & Alerts | Managing addresses
Dialect supports not only messaging via its web3 protocol, but also via email, Telegram, & SMS. Users manage addresss via the Dialect data service, where they may add, verify, update & remove addresses on file for these various channels.
Add a new address
Copy
const address = await sdk.wallet.addresses.create({
type: AddressType.Email,
value: '[email protected]',
});
Verify an address
Dialect uses verification codes to verify ownership of a web2 channel such as email, Telegram or SMS. These codes are sent to the address in question.
Copy
// Verify address (email telegram or phone number). Constraint: there are
// 3 attempts to verify address, otherwise use call below to send new
// verification code
const verifiedAddress = await sdk.wallet.addresses.verify({
addressId: address.id,
code: '1337',
});
If you did not receive the verification code, or if you failed to enter the correct value after several attempts, you can send a new code via the following call:
Copy
// Resend verification code. Constraint: you must wait 60 sec before
// resending the code.
await sdk.wallet.addresses.resendVerificationCode({
addressId: address.id,
});type
Get addresses owned by a wallet
Copy
// Find all addresses owned by wallet
const allAddresses = await sdk.wallet.addresses.findAll();
// Find specific address owned by wallet
const specificAddress = await sdk.wallet.addresses.find({
addressId: address.id,
});
Update an address
You can update an address on file at any time. All of your subscriptions will remain intact, but won't be sent until you re-verify.
Copy
// Update address value
const updatedAddress = await sdk.wallet.addresses.update({
addressId: address.id,
value: '[email protected]',
});
Remove an address
You can delete an address on file at any time. This will remove all subscriptions associated with that address.
Copy
// Delete address
await sdk.wallet.addresses.delete({
addressId: address.id,
});
Previous
Configuration
Next
Subscribing to notifications
Last updated 3 months ago | https://docs.dialect.to/documentation/alerts/alerts-and-monitoring/sdk/typescript/managing-addresses | null |
README.md exists but content is empty.
- Downloads last month
- 38