-
Notifications
You must be signed in to change notification settings - Fork 60
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
4 changed files
with
196 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,97 @@ | ||
--- | ||
title: WharfKit - Multi Session | ||
order: 110 | ||
--- | ||
|
||
# Multi Session with WharfKit | ||
|
||
## Introduction | ||
|
||
WharfKit allows logging in to multiple blockchains as well as using different user accounts. This is useful for applications that need to interact with, for example, an NFT marketplace that allows users to buy and sell NFTs. | ||
|
||
Each time a user logs in to a blockchain, a session is created. A session contains user account information, such as the username, public key, and private key. It also contains blockchain information, such as the blockchain ID. This information is stored in the browser's local storage and is never sent to any server. | ||
|
||
WharfKit can manage multiple sessions for easy switching between them. Let's see how to do it. | ||
|
||
## Understanding the Session Kit | ||
|
||
The session kit is responsible for managing sessions. To do this, it provides a series of methods that allow us to create, and restore sessions. To familiarize ourselves with the session kit, we recommend reading the article [WharfKit - How To React](/build/tutorials/wharfkit/howto_react) in this documentation. | ||
|
||
## Retrieving Sessions | ||
|
||
Thanks to the `getSessions()` method of the session kit, we can retrieve all the sessions that have been created. This method returns an array of sessions, which we can go through to obtain information about each one. | ||
|
||
```javascript | ||
sessionKit | ||
.getSessions() | ||
.then((globalSessions: SerializedSession[] | undefined) => { | ||
if (globalSessions) { | ||
console.log( | ||
'Total sessions retrieved: ', | ||
globalSessions.length | ||
); | ||
} | ||
// filter sessions by blockchain | ||
const sessionsThisChain = globalSessions?.filter( | ||
(session: SerializedSession) => { | ||
return session.chain === chainId; | ||
} | ||
); | ||
// filter sessions by wallet. In this case, Anchor | ||
const sessionsThisWallet = globalSessions?.filter( | ||
(session: SerializedSession) => { | ||
return session.walletPluguin.id === 'anchor'; | ||
} | ||
); | ||
}); | ||
``` | ||
## Switching Sessions | ||
To switch sessions, we simply need to call the `restore()` method of the session kit, passing the session we want to restore as a parameter. This method returns a promise that resolves with the restored session. | ||
```javascript | ||
// .... | ||
const session: SerializedSession = sessionsThisChain[0]; | ||
// .... | ||
|
||
sessionKit.restore(session).then((session: Session | undefined) => { | ||
if (session) { | ||
console.log('Session restored: ', session); | ||
} | ||
}); | ||
``` | ||
The storage of sessions is done in an object of type `SerializedSession`. | ||
```javascript | ||
interface SerializedSession { | ||
actor: NameType; | ||
chain: Checksum256Type; | ||
default?: boolean; | ||
permission: NameType; | ||
walletPlugin: SerializedWalletPlugin; | ||
} | ||
``` | ||
It is worth noting that the `default` attribute indicates whether the session is the default session. This is useful for knowing which session is being used at any given time. | ||
## Adding Sessions | ||
To add a session, we simply need to call the `login()` method of the session kit. This method returns a promise that resolves with the added session. | ||
```javascript | ||
sessionKit.login().then((session: Session | undefined) => { | ||
if (session) { | ||
console.log('Session added: ', session); | ||
} | ||
}); | ||
``` | ||
## Logging Out | ||
To log out of a session, we simply need to call the `logout()` method of the session kit, passing the session we want to close as a parameter. If no parameter is passed, the default session will be closed. | ||
```javascript | ||
sessionKit.logout(session); | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,97 @@ | ||
--- | ||
title: WharfKit - Multi Session | ||
order: 110 | ||
--- | ||
|
||
# Multi Session con WharfKit | ||
|
||
## Introducción | ||
|
||
WharfKit permite iniciar sesión en múltiples cadenas de bloques así como con diferentes cuentas de usuario. Esto es útil para aplicaciones que necesitan interactuar con, como por ejemplo, un mercado de NFTs que permite a los usuarios comprar y vender NFTs. | ||
|
||
Cada vez que un usuario inicia sesión en una cadena de bloques, se crea una sesión. Una sesión contiene la información de la cuenta de usuario, como el nombre de usuario, la clave pública y la clave privada. También contiene la información de la cadena de bloques, como el ID de la cadena de bloques. Esta información se conserva en el almacenamiento local del navegador y nunca se envía a ningún servidor. | ||
|
||
WharfKit puede gestionar múltiples sesiones para poder cambiar entre ellas con facilidad. Veamos cómo hacerlo. | ||
|
||
## Conociendo el Kit de Sesión | ||
|
||
El kit de sesión es el encargado de gestionar las sesiones. Para ello, proporciona una serie de métodos que nos permiten crear, y restaurar sesiones. Para familiarizarnos con el kit de sesión recomendamos la lectura del artículo [WharfKit - How To React](/es/build/tutorials/wharfkit/howto_react) de esta documentación. | ||
|
||
## Recuperando Sesiones | ||
|
||
Gracias al método `getSessions()` del kit de sesión, podemos recuperar todas las sesiones que se han creado. Este método devuelve un array de sesiones, que podemos recorrer para obtener la información de cada una de ellas. | ||
|
||
```javascript | ||
sessionKit | ||
.getSessions() | ||
.then((globalSessions: SerializedSession[] | undefined) => { | ||
if (globalSessions) { | ||
console.log( | ||
'Total de sesiones recuperadas: ', | ||
globalSessions.length | ||
); | ||
} | ||
// filtrar las sesiones por cadena de bloques | ||
const sessionsThisChain = globalSessions?.filter( | ||
(session: SerializedSession) => { | ||
return session.chain === chainId; | ||
} | ||
); | ||
// filtrar las sesiones por wallet. En este caso, Anchor | ||
const sessionsThisWallet = globalSessions?.filter( | ||
(session: SerializedSession) => { | ||
return session.walletPluguin.id === 'anchor'; | ||
} | ||
); | ||
}); | ||
``` | ||
## Cambiar de Sesión | ||
Para cambiar de sesión, simplemente necesitamos llamar al método `restore()` del kit de sesión, pasando como parámetro la sesión que queremos restaurar. Este método devuelve una promesa que se resuelve con la sesión restaurada. | ||
```javascript | ||
// .... | ||
const session: SerializedSession = sessionsThisChain[0]; | ||
// .... | ||
|
||
sessionKit.restore(session).then((session: Session | undefined) => { | ||
if (session) { | ||
console.log('Sesión restaurada: ', session); | ||
} | ||
}); | ||
``` | ||
El almacenamiento de las sesiones se realiza en un objeto de tipo `SerializedSession`. | ||
```javascript | ||
interface SerializedSession { | ||
actor: NameType; | ||
chain: Checksum256Type; | ||
default?: boolean; | ||
permission: NameType; | ||
walletPlugin: SerializedWalletPlugin; | ||
} | ||
``` | ||
Cabe destacar que el atributo ```default``` es el que indica si la sesión es la sesión por defecto. Esto es útil para saber qué sesión se está utilizando en cada momento. | ||
## Agregar Sesiones | ||
Para agregar una sesión, simplemente necesitamos llamar al método `login()` del kit de sesión. Este método devuelve una promesa que se resuelve con la sesión agregada. | ||
```javascript | ||
sessionKit.login().then((session: Session | undefined) => { | ||
if (session) { | ||
console.log('Sesión agregada: ', session); | ||
} | ||
}); | ||
``` | ||
## Cerrar Sesión | ||
Para cerrar una sesión, simplemente necesitamos llamar al método `logout()` del kit de sesión, pasando como parámetro la sesión que queremos cerrar. Si no se pasa ningún parámetro, se cerrará la sesión por defecto. | ||
```javascript | ||
sessionKit.logout(session); | ||
``` |