Functions
This section provides detailed documentation for the global and utility functions available in the Blocklet SDK. These functions cover a wide range of functionalities, including inter-component communication, security operations, wallet management, environment access, and event handling.
For an overview of core services and their related functionalities, refer to the Core Services section. For utility modules, see Utilities.
component.call()#
Allows a Blocklet to make an HTTP request to another component running on the same Blocklet Server. This function is essential for inter-component communication.
Parameters
Name | Type | Description |
---|---|---|
|
| An object containing request configuration. |
|
| The name or DID of the target component. This is a required field. |
|
| The HTTP method (e.g., |
|
| The API path on the target component (e.g., |
|
| The request body data for |
|
| URL query parameters. |
|
| Custom HTTP headers. |
|
| Request timeout in milliseconds. |
|
| Optional. Configuration for request retries. |
|
| Number of retries on failure. Defaults to |
|
| The exponential backoff factor. Defaults to |
|
| Whether to randomize the backoff time. Defaults to |
|
| Minimum timeout between retries in milliseconds. Defaults to |
|
| Maximum timeout between retries in milliseconds. Defaults to |
|
| Callback function executed on each failed attempt. |
Returns
Name | Type | Description |
---|---|---|
|
| The Axios response object from the component call. If |
Example
import { component } from '@blocklet/sdk';
async function callAnotherComponent() {
try {
const response = await component.call({
name: 'my-other-component-name', // Or DID: 'zNKjJ5K5mYf1...'
method: 'GET',
path: '/api/status',
headers: { 'X-Custom-Header': 'value' },
});
console.log('Component response:', response.data);
} catch (error) {
console.error('Error calling component:', error.message);
}
}
callAnotherComponent();
Example Response
{
"data": {
"status": "running",
"message": "Service is operational"
},
"status": 200,
"statusText": "OK",
"headers": {},
"config": {},
"request": {}
}
This example demonstrates how to make a GET request to another component named my-other-component-name
on the /api/status
path and log its response. The function automatically handles retries for transient errors.
component.getUrl()#
Constructs an absolute URL for a given path within the current component's context, based on the Blocklet Server's BLOCKLET_APP_URL
and the component's mount point.
Parameters
Name | Type | Description |
---|---|---|
|
| Path segments to append to the base URL. |
Returns
Name | Type | Description |
---|---|---|
|
| The fully qualified URL. |
Example
import { component } from '@blocklet/sdk';
function getMyApiUrl() {
// Assumes BLOCKLET_APP_URL='https://my-app.com' and component mounted at '/my-component'
const apiUrl = component.getUrl('api', 'data', 'v1');
console.log('Absolute API URL:', apiUrl);
}
getMyApiUrl();
Example Response
"https://my-app.com/my-component/api/data/v1"
This example generates an absolute URL to https://my-app.com/my-component/api/data/v1
assuming the application is deployed at https://my-app.com
and the current component is mounted at /my-component
.
component.getRelativeUrl()#
Constructs a relative URL for a given path within the current component's context, starting from the component's mount point.
Parameters
Name | Type | Description |
---|---|---|
|
| Path segments to append to the component's mount point. |
Returns
Name | Type | Description |
---|---|---|
|
| The relative URL. |
Example
import { component } from '@blocklet/sdk';
function getMyRelativeAssetUrl() {
// Assumes component mounted at '/my-component'
const assetUrl = component.getRelativeUrl('assets', 'image.png');
console.log('Relative asset URL:', assetUrl);
}
getMyRelativeAssetUrl();
Example Response
"/my-component/assets/image.png"
This example generates a relative URL to /my-component/assets/image.png
assuming the current component is mounted at /my-component
.
component.getComponentMountPoint()#
Retrieves the mount point (URL prefix) of a specified component.
Parameters
Name | Type | Description |
---|---|---|
|
| The name or DID of the component. |
Returns
Name | Type | Description |
---|---|---|
|
| The mount point of the component, or an empty string if not found. |
Example
import { component } from '@blocklet/sdk';
function getMountPoint(componentName) {
const mountPoint = component.getComponentMountPoint(componentName);
console.log(`Mount point for ${componentName}:`, mountPoint);
}
getMountPoint('my-other-component');
getMountPoint('non-existent-component');
Example Response
"/my-other-component"
This example retrieves and logs the mount point for my-other-component
.
component.getComponentWebEndpoint()#
Retrieves the web endpoint URL for a specified component. This is particularly useful for direct communication with a component's web server within the Docker environment.
Parameters
Name | Type | Description |
---|---|---|
|
| The name or DID of the component. |
Returns
Name | Type | Description |
---|---|---|
|
| The web endpoint URL of the component, or an empty string if not found. |
Example
import { component } from '@blocklet/sdk';
function getWebEndpoint(componentName) {
const webEndpoint = component.getComponentWebEndpoint(componentName);
console.log(`Web endpoint for ${componentName}:`, webEndpoint);
}
getWebEndpoint('my-other-component');
Example Response
"http://172.17.0.3:3030"
This example retrieves and logs the internal web endpoint for my-other-component
.
component.waitForComponentRunning()#
Waits until a specified component is running and accessible on its assigned port. This is useful for ensuring dependencies are ready before proceeding.
Parameters
Name | Type | Description |
---|---|---|
|
| The name or DID of the component to wait for. |
|
| Optional. The maximum time to wait in milliseconds. Defaults to |
|
| Optional. The interval between port checks in milliseconds. Defaults to |
Returns
Name | Type | Description |
---|---|---|
|
| A Promise that resolves to |
Example
import { component } from '@blocklet/sdk';
async function ensureComponentIsReady(componentName) {
try {
console.log(`Waiting for component ${componentName} to start...`);
await component.waitForComponentRunning(componentName, 60000); // Wait up to 60 seconds
console.log(`Component ${componentName} is running.`);
} catch (error) {
console.error(`Component ${componentName} did not start in time:`, error.message);
}
}
ensureComponentIsReady('my-database-component');
Example Response
(No direct JSON response, as it's an async operation that resolves or rejects)
Component my-database-component is running.
This example waits for my-database-component
to be running for up to 60 seconds. If it's not ready, an error will be logged.
component.getResourceExportDir()#
Determines the directory path where resources are exported for a specific project and optional release. This is typically within the Blocklet Server's data directory structure.
Parameters
Name | Type | Description |
---|---|---|
|
| An object containing project and release IDs. |
|
| The ID of the project. This is a required field. |
|
| Optional. The ID of the specific release. |
Returns
Name | Type | Description |
---|---|---|
|
| The absolute path to the resource export directory. |
Example
import { component } from '@blocklet/sdk';
function getResourceDir() {
const projectId = 'my-project-did';
const releaseId = 'my-release-id';
const resourceDir = component.getResourceExportDir({ projectId, releaseId });
console.log('Resource export directory:', resourceDir);
const projectResourceDir = component.getResourceExportDir({ projectId });
console.log('Project-level resource export directory:', projectResourceDir);
}
getResourceDir();
Example Response
"/mnt/blocklet/data/app/data/projects/my-project-did/releases/my-release-id/resources"
This example demonstrates how to get the resource export directory for a specific project and release, or just for a project.
component.getReleaseExportDir()#
Determines the directory path where release artifacts are exported for a specific project and optional release. This is within the Blocklet Server's data directory structure.
Parameters
Name | Type | Description |
---|---|---|
|
| An object containing project and release IDs. |
|
| The ID of the project. This is a required field. |
|
| Optional. The ID of the specific release. |
Returns
Name | Type | Description |
---|---|---|
|
| The absolute path to the release export directory. |
Example
import { component } from '@blocklet/sdk';
function getReleaseDir() {
const projectId = 'my-project-did';
const releaseId = 'my-release-id';
const releaseDir = component.getReleaseExportDir({ projectId, releaseId });
console.log('Release export directory:', releaseDir);
const projectReleaseDir = component.getReleaseExportDir({ projectId });
console.log('Project-level release export directory:', projectReleaseDir);
}
getReleaseDir();
Example Response
"/mnt/blocklet/data/app/data/projects/my-project-did/releases/my-release-id"
This example shows how to get the release export directory for a given project and optional release.
component.getResources()#
Retrieves a list of resources associated with installed components, with options to filter by scope and type.
Parameters
Name | Type | Description |
---|---|---|
|
| Optional. An object for filtering resources. |
|
| Optional. The scope of resources to retrieve. |
|
| Optional. An array of objects to filter resources by DID and type. |
|
| Optional. If |
Returns
Name | Type | Description |
---|---|---|
|
| An array of resource objects. Each |
Example
import { component } from '@blocklet/sdk';
function listResources() {
const allResources = component.getResources();
console.log('All resources:', allResources);
const packResources = component.getResources({ scope: 'pack' });
console.log('Pack resources:', packResources);
const specificTypeResources = component.getResources({
types: [{ did: 'zNKjJ5K5mYf1...', type: 'asset' }],
});
console.log('Specific type resources:', specificTypeResources);
}
listResources();
Example Response
[
{
"did": "zNKjJ5K5mYf1...",
"type": "dapp",
"mountPoint": "/my-dapp",
"webEndpoint": "http://172.17.0.3:3030",
"status": 1 // BlockletStatus.running
},
{
"did": "zNKeL3Wc...",
"type": "service",
"mountPoint": "/my-service",
"status": 0 // BlockletStatus.stopped
}
]
This example demonstrates how to retrieve all resources, only pack
resources, and resources filtered by a specific DID and type.
component.getPackResources()#
Retrieves a list of resources specifically marked as 'pack' resources. This is a convenience function that calls getResources
with scope: 'pack'
and ignorePublic: true
.
Parameters
Name | Type | Description |
---|---|---|
|
| Optional. An object for filtering resources. |
|
| Optional. An array of objects to filter resources by DID and type. |
Returns
Name | Type | Description |
---|---|---|
|
| An array of resource objects that are part of the pack. |
Example
import { component } from '@blocklet/sdk';
function listPackResources() {
const packResources = component.getPackResources();
console.log('All pack resources:', packResources);
const specificPackTypeResources = component.getPackResources({
types: [{ did: 'zNKjJ5K5mYf1...', type: 'theme' }],
});
console.log('Specific pack type resources:', specificPackTypeResources);
}
listPackResources();
Example Response
[
{
"did": "zNKaL5B8...",
"type": "theme",
"mountPoint": "/my-theme",
"webEndpoint": "http://172.17.0.4:4040",
"status": 1
}
]
This example retrieves and logs all resources that are part of the current Blocklet's pack.
security.encrypt()#
Encrypts a message using AES encryption with a key derived from the Blocklet's environment variables (BLOCKLET_APP_EK
and BLOCKLET_DID
).
Parameters
Name | Type | Description |
---|---|---|
|
| The string message to encrypt. |
|
| Optional. A custom password for encryption. If not provided, |
|
| Optional. A custom salt for key derivation. If not provided, |
Returns
Name | Type | Description |
---|---|---|
|
| The encrypted message string. If |
Example
import { security } from '@blocklet/sdk';
function encryptData(data) {
const encrypted = security.encrypt(data);
console.log('Encrypted data:', encrypted);
const customEncrypted = security.encrypt('sensitive info', 'myStrongPassword', 'myCustomSalt');
console.log('Custom encrypted data:', customEncrypted);
}
encryptData('This is a secret message.');
Example Response
"U2FsdGVkX1+vGzQy..."
This example encrypts a message using the default Blocklet environment keys and also demonstrates encryption with custom keys.
security.decrypt()#
Decrypts an AES encrypted message using a key derived from the Blocklet's environment variables (BLOCKLET_APP_EK
and BLOCKLET_DID
).
Parameters
Name | Type | Description |
---|---|---|
|
| The encrypted message string to decrypt. |
|
| Optional. A custom password used for encryption. If not provided, |
|
| Optional. A custom salt used for encryption. If not provided, |
Returns
Name | Type | Description |
---|---|---|
|
| The decrypted message string. If |
Example
import { security } from '@blocklet/sdk';
function decryptData(encryptedData) {
const decrypted = security.decrypt(encryptedData);
console.log('Decrypted data:', decrypted);
const customDecrypted = security.decrypt('U2FsdGVkX1+vGzQy...', 'myStrongPassword', 'myCustomSalt');
console.log('Custom decrypted data:', customDecrypted);
}
decryptData('U2FsdGVkX1+vGzQy...'); // Replace with an actual encrypted string
Example Response
"This is a secret message."
This example decrypts an encrypted message using the default Blocklet environment keys and also demonstrates decryption with custom keys.
security.signResponse()#
Signs a given data object using the Blocklet's internal wallet. This ensures data integrity and authenticity.
Parameters
Name | Type | Description |
---|---|---|
|
| The data object to be signed. |
Returns
Name | Type | Description |
---|---|---|
|
| The original data object with a |
Example
import { security } from '@blocklet/sdk';
async function signMyData() {
const payload = { message: 'Hello Blocklet!', timestamp: Date.now() };
const signedPayload = security.signResponse(payload);
console.log('Signed payload:', signedPayload);
}
signMyData();
Example Response
{
"message": "Hello Blocklet!",
"timestamp": 1678886400000,
"_signature": "0x..."
}
This example signs a simple data payload, adding a digital signature to it.
security.verifyResponse()#
Verifies the digital signature of a data object, ensuring its integrity and that it was signed by the expected Blocklet's wallet.
Parameters
Name | Type | Description |
---|---|---|
|
| The data object containing a |
Returns
Name | Type | Description |
---|---|---|
|
|
|
Example
import { security } from '@blocklet/sdk';
async function verifyReceivedData(signedData) {
const isValid = security.verifyResponse(signedData);
console.log('Signature is valid:', isValid);
}
// Example usage with a previously signed payload
const exampleSignedData = {
message: 'Hello Blocklet!',
timestamp: 1678886400000,
_signature: '0x...'
};
verifyReceivedData(exampleSignedData);
Example Response
true
This example verifies the signature of a received data object.
getWallet()#
Retrieves the Blocklet's internal wallet object. This function is overloaded to support different wallet types and can be used to get the primary application wallet or specific types like Ethereum wallets.
Parameters
Name | Type | Description |
---|---|---|
|
| Optional. The type of DID wallet to retrieve ( |
|
| Optional. The application's secret key. Defaults to |
Returns
Name | Type | Description |
---|---|---|
|
| The wallet object. |
Example
import getWallet from '@blocklet/sdk/lib/wallet';
function retrieveWallets() {
const defaultWallet = getWallet();
console.log('Default Blocklet Wallet DID:', defaultWallet.toDID());
const permanentWallet = getWallet.getPermanentWallet();
console.log('Permanent Blocklet Wallet DID:', permanentWallet.toDID());
const ethereumWallet = getWallet.getEthereumWallet();
console.log('Ethereum Blocklet Wallet Address:', ethereumWallet.toAddress());
const pkWallet = getWallet.getPkWallet('default', process.env.BLOCKLET_APP_PK);
console.log('Wallet from Public Key DID:', pkWallet.toDID());
}
retrieveWallets();
Example Response
"did:abt:zNKjJ5K5mYf1..."
This example demonstrates how to retrieve the default, permanent, Ethereum, and public-key derived wallets for the Blocklet.
getLoginProvider()#
Retrieves the login provider used for the current request, typically from request query parameters or context store.
Parameters
Name | Type | Description |
---|---|---|
|
| The incoming HTTP request object, typically an Express.js request object. |
Returns
Name | Type | Description |
---|---|---|
|
| The login provider (e.g., |
Example
import { getLoginProvider } from '@blocklet/sdk/lib/util/login';
// In an Express.js route handler
function handleLoginRequest(req, res) {
const provider = getLoginProvider(req);
console.log('Login provider:', provider);
res.send(`Using provider: ${provider}`);
}
// Example usage (simulated request)
const mockRequest = { query: { provider: 'PASSPORT' }, context: { store: { extraParams: {} } } };
handleLoginRequest(mockRequest, {});
const anotherMockRequest = { query: {}, context: { store: { extraParams: { provider: 'WALLET' } } } };
handleLoginRequest(anotherMockRequest, {});
Example Response
"PASSPORT"
This example shows how to extract the login provider from an incoming request.
getSourceAppPid()#
Retrieves the sourceAppPid
from the request, which indicates the PID of the application that initiated the login or operation.
Parameters
Name | Type | Description |
---|---|---|
|
| The incoming HTTP request object, typically an Express.js request object. |
Returns
Name | Type | Description |
---|---|---|
|
| The source application PID, or |
Example
import { getSourceAppPid } from '@blocklet/sdk/lib/util/login';
// In an Express.js route handler
function handleRequestWithSourcePid(req, res) {
const sourcePid = getSourceAppPid(req);
console.log('Source App PID:', sourcePid);
res.send(`Source App PID: ${sourcePid}`);
}
// Example usage (simulated request)
const mockRequest = { query: { sourceAppPid: 'app_pid_123' }, context: { store: { extraParams: {} } } };
handleRequestWithSourcePid(mockRequest, {});
const anotherMockRequest = { query: {}, context: { store: { extraParams: { sourceAppPid: 'app_pid_456' } } } };
handleRequestWithSourcePid(anotherMockRequest, {});
Example Response
"app_pid_123"
This example shows how to get the sourceAppPid
from an incoming request.
encodeKycStatus()#
Encodes the KYC (Know Your Customer) verification status (email and phone) into a single integer bitmask.
Parameters
Name | Type | Description |
---|---|---|
|
|
|
|
|
|
Returns
Name | Type | Description |
---|---|---|
|
| An integer representing the encoded KYC status. |
Example
import { encodeKycStatus } from '@blocklet/sdk/lib/util/login';
function demonstrateKycEncoding() {
console.log('Email verified, Phone not:', encodeKycStatus(true, false)); // Expected: 1
console.log('Email not, Phone verified:', encodeKycStatus(false, true)); // Expected: 2
console.log('Both verified:', encodeKycStatus(true, true)); // Expected: 3
console.log('Neither verified:', encodeKycStatus(false, false)); // Expected: 0
}
demonstrateKycEncoding();
Example Response
1
This example demonstrates how different combinations of email and phone verification statuses are encoded into an integer.
decodeKycStatus()#
Decodes an integer bitmask back into individual KYC (Know Your Customer) verification statuses for email and phone.
Parameters
Name | Type | Description |
---|---|---|
|
| The integer representing the encoded KYC status. |
Returns
Name | Type | Description |
---|---|---|
|
| An object containing |
|
|
|
|
|
|
Example
import { decodeKycStatus } from '@blocklet/sdk/lib/util/login';
function demonstrateKycDecoding() {
console.log('Decoding 1:', decodeKycStatus(1)); // Expected: { emailVerified: true, phoneVerified: false }
console.log('Decoding 2:', decodeKycStatus(2)); // Expected: { emailVerified: false, phoneVerified: true }
console.log('Decoding 3:', decodeKycStatus(3)); // Expected: { emailVerified: true, phoneVerified: true }
console.log('Decoding 0:', decodeKycStatus(0)); // Expected: { emailVerified: false, phoneVerified: false }
}
demonstrateKycDecoding();
Example Response
{
"emailVerified": true,
"phoneVerified": false
}
This example shows how to decode the KYC status integer back into its boolean components.
isLoginToken()#
Checks if a given string is a valid login token format (typically a JWT with three parts separated by dots).
Parameters
Name | Type | Description |
---|---|---|
|
| The string to check. |
Returns
Name | Type | Description |
---|---|---|
|
|
|
Example
import { isLoginToken } from '@blocklet/sdk/lib/util/login';
function checkTokens() {
console.log('Valid login token:', isLoginToken('header.payload.signature'));
console.log('Invalid token (two parts):', isLoginToken('header.payload'));
console.log('Invalid token (one part):', isLoginToken('just_a_string'));
}
checkTokens();
Example Response
true
This example demonstrates how to validate the format of a login token string.
isAccessKey()#
Checks if a given string is a valid access key format (starts with blocklet-
and has only one part).
Parameters
Name | Type | Description |
---|---|---|
|
| The string to check. |
Returns
Name | Type | Description |
---|---|---|
|
|
|
Example
import { isAccessKey } from '@blocklet/sdk/lib/util/login';
function checkAccessKeys() {
console.log('Valid access key:', isAccessKey('blocklet-abcdef123456'));
console.log('Invalid access key (wrong prefix):', isAccessKey('some-other-key'));
console.log('Invalid access key (multiple parts):', isAccessKey('blocklet-key.part2'));
}
checkAccessKeys();
Example Response
true
This example demonstrates how to validate the format of an access key string.
did.getUserInfo()#
Retrieves detailed user information for a given DID, optionally using a specific AuthService
client. This includes connected accounts if enabled.
Parameters
Name | Type | Description |
---|---|---|
|
| The DID of the user to retrieve information for. |
|
| Optional. An object for configuration. |
|
| Optional. An instance of |
Returns
Name | Type | Description |
---|---|---|
|
| The user object containing details like |
Example
import { getUserInfo } from '@blocklet/sdk/lib/did';
async function fetchUserInfo(did) {
try {
const user = await getUserInfo(did);
console.log('User Info:', user);
console.log('User DID:', user.did);
console.log('User Full Name:', user.fullName);
if (user.connectedAccounts) {
console.log('Connected Accounts:', user.connectedAccounts);
}
} catch (error) {
console.error(`Error fetching user info for ${did}:`, error.message);
}
}
fetchUserInfo('did:abt:zNKjJ5K5mYf1...'); // Replace with a valid user DID
Example Response
{
"did": "did:abt:zNKjJ5K5mYf1...",
"role": "user",
"provider": "WALLET",
"fullName": "John Doe",
"walletOS": "iOS",
"emailVerified": true,
"phoneVerified": false,
"method": "loginToken",
"kyc": 1,
"connectedAccounts": [
{
"did": "did:eth:0x...",
"type": "ethereum",
"chainHost": "https://arcblock.io/",
"status": "connected"
}
]
}
This example fetches and logs the detailed information for a specified user DID.
did.toBlockletDid()#
Converts a DID string into a normalized Blocklet DID format.
Parameters
Name | Type | Description |
---|---|---|
|
| The DID string to normalize. |
Returns
Name | Type | Description |
---|---|---|
|
| The normalized Blocklet DID. |
Example
import { toBlockletDid } from '@blocklet/sdk/lib/did';
function normalizeDid() {
const normalized = toBlockletDid('did:abt:zNKjJ5K5mYf1...');
console.log('Normalized Blocklet DID:', normalized);
}
normalizeDid();
Example Response
"did:abt:zNKjJ5K5mYf1..."
This example demonstrates normalizing a DID string to the Blocklet DID format.
did.getConnectedAccounts()#
Retrieves a list of connected accounts associated with a user's DID, such as linked Ethereum addresses or other DIDs.
Parameters
Name | Type | Description |
---|---|---|
|
| The DID of the user whose connected accounts are to be retrieved. |
Returns
Name | Type | Description |
---|---|---|
|
| An array of connected account objects. Each object typically includes |
Example
import { getConnectedAccounts } from '@blocklet/sdk/lib/did';
async function fetchConnectedAccounts(userDid) {
try {
const accounts = await getConnectedAccounts(userDid);
console.log(`Connected accounts for ${userDid}:`, accounts);
} catch (error) {
console.error(`Error fetching connected accounts for ${userDid}:`, error.message);
}
}
fetchConnectedAccounts('did:abt:zNKjJ5K5mYf1...'); // Replace with a valid user DID
Example Response
[
{
"did": "did:eth:0x123...",
"type": "ethereum",
"chainHost": "https://arcblock.io/",
"status": "connected"
},
{
"did": "did:abt:zNKu...",
"type": "abt",
"chainHost": "https://arcblock.io/",
"status": "connected"
}
]
This example fetches and logs the connected accounts for a specified user DID.
did.getConnectedDids()#
Retrieves a list of DIDs connected to a user's primary DID.
Parameters
Name | Type | Description |
---|---|---|
|
| The DID of the user whose connected DIDs are to be retrieved. |
Returns
Name | Type | Description |
---|---|---|
|
| An array of connected DID strings. |
Example
import { getConnectedDids } from '@blocklet/sdk/lib/did';
async function fetchConnectedDids(userDid) {
try {
const connectedDids = await getConnectedDids(userDid);
console.log(`Connected DIDs for ${userDid}:`, connectedDids);
} catch (error) {
console.error(`Error fetching connected DIDs for ${userDid}:`, error.message);
}
}
fetchConnectedDids('did:abt:zNKjJ5K5mYf1...'); // Replace with a valid user DID
Example Response
[
"did:eth:0x123...",
"did:abt:zNKu..."
]
This example fetches and logs the DIDs connected to a specified user's DID.
did.getPermanentDid()#
Retrieves the permanent DID associated with the Blocklet application. This DID is derived from BLOCKLET_APP_PSK
(Permanent Secret Key) and remains constant even if BLOCKLET_APP_SK
changes.
Parameters
This function takes no parameters.
Returns
Name | Type | Description |
---|---|---|
|
| The permanent DID of the Blocklet. |
Example
import { getPermanentDid } from '@blocklet/sdk/lib/did';
function getAppPermanentDid() {
const permanentDid = getPermanentDid();
console.log('Blocklet Permanent DID:', permanentDid);
}
getAppPermanentDid();
Example Response
"did:abt:zNKjJ5K5mYfP..."
This example retrieves and logs the permanent DID of the Blocklet application.
did.getWalletDid()#
Retrieves the DID of the Blocklet's internal wallet. This is typically the application's primary DID derived from BLOCKLET_APP_SK
.
Parameters
This function takes no parameters.
Returns
Name | Type | Description |
---|---|---|
|
| The DID of the Blocklet's wallet. |
Example
import { getWalletDid } from '@blocklet/sdk/lib/did';
function getAppWalletDid() {
const walletDid = getWalletDid();
console.log('Blocklet Wallet DID:', walletDid);
}
getAppWalletDid();
Example Response
"did:abt:zNKjJ5K5mYf1..."
This example retrieves and logs the DID of the Blocklet's primary wallet.
eventbus.subscribe()#
Subscribes a callback function to the Blocklet Server's internal event bus, allowing the component to receive events.
Parameters
Name | Type | Description |
---|---|---|
|
| The callback function to be executed when an event is received. It takes an event object as its argument. |
Returns
This function returns nothing.
Example
import { subscribe } from '@blocklet/sdk/lib/service/eventbus';
function handleEvent(event) {
console.log('Received event:', event.type, event.data);
// Process the event data
}
function setupEventSubscription() {
console.log('Subscribing to events...');
subscribe(handleEvent);
console.log('Subscribed. Waiting for events...');
}
setupEventSubscription();
Example Response
(No direct JSON response, as it sets up a listener)
Received event: user_registered { did: 'did:abt:zNKjJ5K5mYf1...', name: 'New User' }
This example subscribes to the event bus and logs any incoming events. The handleEvent
function will be called whenever an event is published on the bus.
eventbus.unsubscribe()#
Unsubscribes a previously registered callback function from the Blocklet Server's internal event bus, stopping the component from receiving further events for that specific listener.
Parameters
Name | Type | Description |
---|---|---|
|
| The exact same callback function that was previously subscribed. |
Returns
This function returns nothing.
Example
import { subscribe, unsubscribe } from '@blocklet/sdk/lib/service/eventbus';
function myEventHandler(event) {
console.log('Event received:', event.type);
}
function manageSubscription() {
console.log('Subscribing...');
subscribe(myEventHandler);
// After some time or condition, unsubscribe
setTimeout(() => {
console.log('Unsubscribing...');
unsubscribe(myEventHandler);
console.log('Unsubscribed. No more events will be received by this handler.');
}, 5000);
}
manageSubscription();
Example Response
(No direct JSON response, as it manages a listener)
Subscribing...
Event received: some_event_type
Unsubscribing...
Unsubscribed. No more events will be received by this handler.
This example demonstrates how to unsubscribe a myEventHandler
function after a 5-second delay.
eventbus.publish()#
Publishes a custom event to the Blocklet Server's internal event bus. Events can be consumed by other components subscribed to the bus.
Parameters
Name | Type | Description |
---|---|---|
|
| The name or type of the event (e.g., |
|
| An object containing the event details. |
|
| Optional. A unique ID for the event. If not provided, a random ID is generated. |
|
| Optional. The timestamp of the event in ISO 8601 format. If not provided, the current time is used. |
|
| The payload data of the event. Must contain |
|
| The type of the object related to the event (e.g., |
|
| The ID of the object related to the event. |
|
| Additional custom data fields for the event. |
Returns
Name | Type | Description |
---|---|---|
|
| A Promise that resolves when the event is successfully published. |
Example
import { publish } from '@blocklet/sdk/lib/service/eventbus';
async function publishUserCreatedEvent(userDid, userName) {
try {
await publish('user_created', {
data: {
object_type: 'user',
object_id: userDid,
name: userName,
source: process.env.BLOCKLET_COMPONENT_DID // Optional, but good practice
},
});
console.log(`Event 'user_created' for user ${userDid} published successfully.`);
} catch (error) {
console.error('Failed to publish event:', error.message);
}
}
publishUserCreatedEvent('did:abt:zNKjJ5K5mYf1...', 'Alice');
Example Response
(No direct JSON response, as it's an async operation that resolves or rejects)
Event 'user_created' for user did:abt:zNKjJ5K5mYf1... published successfully.
This example publishes a user_created
event with the user's DID and name as data. Other subscribed components can then react to this event.
config.setLogger()#
Sets a custom logger for the Blocklet SDK. This allows developers to integrate the SDK's logs into their existing logging infrastructure.
Parameters
Name | Type | Description |
---|---|---|
|
| An object conforming to the logger interface, typically with |
|
| Log informational messages. |
|
| Log debug messages. |
|
| Log warning messages. |
|
| Log error messages. |
Returns
This function returns nothing.
Example
import { setLogger, logger } from '@blocklet/sdk/lib/config';
const customLogger = {
info: (...args) => console.log('[INFO]', ...args),
debug: (...args) => console.log('[DEBUG]', ...args),
warn: (...args) => console.warn('[WARN]', ...args),
error: (...args) => console.error('[ERROR]', ...args),
};
// Set the custom logger
setLogger(customLogger);
// Now, SDK's internal logs will use your custom logger
logger.info('This message uses the custom logger.');
logger.error('An error occurred in the SDK.');
Example Response
(No direct JSON response, as it configures logging)
[INFO] This message uses the custom logger.
[ERROR] An error occurred in the SDK.
This example demonstrates how to replace the default console logger with a custom logger that prefixes log messages.
config.getBlockletJs()#
Retrieves the window.blocklet
JavaScript content, which contains Blocklet Server and component-specific configuration, dynamically injected into the frontend. This function allows for customization of the pageGroup
and pathPrefix
.
Parameters
Name | Type | Description |
---|---|---|
|
| Optional. The page group to inject into the |
|
| Optional. The path prefix to inject into the |
|
| Optional. The raw |
Returns
Name | Type | Description |
---|---|---|
|
| The JavaScript string containing the |
Example
import { getBlockletJs } from '@blocklet/sdk/lib/config';
function getFrontendConfig() {
const jsContent = getBlockletJs('/admin', '/admin/my-component');
console.log('Generated Blocklet.js content (excerpt):', jsContent.substring(0, 200) + '...');
}
getFrontendConfig();
Example Response
(No direct JSON response, as it returns a JS string)
"window.blocklet = {\n serverDid: "did:abt:zNK...",\n serverVersion: "1.17.0",\n did: "did:abt:zNK...",\n appId: "zNK...",\n appIds: ["zNK..."],\n appPid: "zNK...",\n appPk: "zNK...",\n appName: "My Blocklet App",\n appDescription: "A Blocklet app",\n appLogo: "/logo.png",\n appLogoRect: "/logo-rect.png",\n appUrl: "https://my-app.com",\n webWalletUrl: "https://wallet.arcblock.io",\n isComponent: true,\n prefix: "/admin/my-component/",\n groupPrefix: "/admin/",\n pageGroup: "/admin",\n version: "1.0.0",\n mode: "production",\n status: "running",\n tenantMode: "single",\n theme: {...},\n navigation: [...],\n preferences: {...},\n languages: [...],\n passportColor: "#007AFF",\n componentId: "zNK...",\n componentMountPoints: [...],\n alsoKnownAs: [...],\n trustedFactories: [...],\n updatedAt: 1678886400000,\n settings: {...}\n};"
This example generates a window.blocklet
script with a specified pageGroup
and pathPrefix
.
config.getBlockletSettings()#
Retrieves the Blocklet's consolidated settings, including theme preferences and other configurations, typically derived from __blocklet__.json
and environment variables.
Parameters
This function takes no parameters.
Returns
Name | Type | Description |
---|---|---|
|
| The Blocklet's settings object, including theme, session, federated, and OAuth configurations. |
Example
import { getBlockletSettings } from '@blocklet/sdk/lib/config';
function getSettings() {
const settings = getBlockletSettings();
console.log('Blocklet Settings:', settings);
console.log('Theme preference:', settings.theme.prefer);
}
getSettings();
Example Response
{
"theme": {
"prefer": "system",
"light": {
"palette": {
"primary": "#007AFF",
"background": "#FFFFFF"
}
},
"dark": {
"palette": {
"primary": "#66B3FF",
"background": "#1A1A1A"
}
}
},
"session": {
"ttl": 3600,
"cacheTtl": 300
},
"federated": {
"master": {
"appId": "did:abt:zNK...",
"appPid": "zNK...",
"appName": "Federated Master App",
"appDescription": "",
"appUrl": "https://master.example.com",
"appLogo": "",
"version": "1.0.0"
},
"config": {}
},
"oauth": {
"github": {
"enabled": true,
"clientId": "abc",
"clientSecret": "xyz"
}
}
}
This example retrieves and logs the Blocklet's current settings, including theme and session configurations.
This section provided a comprehensive overview of the global and utility functions available in the Blocklet SDK. These functions are crucial for interacting with the Blocklet Server environment, managing components, handling security, and facilitating various application-level operations.
To learn more about the SDK's class-based APIs, proceed to the Classes section. For an overview of types and enums, see Types & Enums.