Перейти к содержанию

Self-Custody Use Case (XLM)

This guide illustrates the creation of secrets, address synchronization, balance retrieval, and transaction sending from a client wallet application within Self-Custody using Spatium Signer Service.

Initialization

To interact with Spatium Signer Client, you need to provide the following data:

import { MemoryStorageDriver, SpatiumCrypto } from '@spatium/sdk';
import { AuthorizationSession, ServiceStorage, SignerClient } from '@spatium/signer-client';

export const createSignerClient = (auth: AuthorizationSession) => {
    const storage = new ServiceStorage('https://cloud.spatium.net/storage/v1', auth);

    const cache = new MemoryStorageDriver()
    const crypto = new SpatiumCrypto(cache, storage)

    return new SignerClient('https://cloud.spatium.net/signer/v1', auth, crypto, 10 * 1000);  
};

Important! In this example, ServiceStorage is used as a storage, which places both secrets at Spatium. The use of this format implies that the wallet is custodial. It's not recommended for production use.

Secret Generation

To use a distributed wallet, you need to generate a permanent pair of client and server secrets and ensure their secure storage. On the Spatium Signer Service side, secret management is automated, while on the client side, the developer must implement a stableStorageDriver on their own. In both cases, the secret is bound to its identifier (secretId) and is accessible through it after creation. A user can have any number of secrets, but to ensure their security and recoverability, it is recommended to use one secret per user.

To backup secrets in case of StorageDriver content loss, it is recommended to use export and import features.

export const ensureSecret = async (signerClient: SignerClient, secretId: string) => {
  if (await signerClient.crypto.checkSecret(secretId)) {
    return;
  }

  try {
    // Wait for the actual connection to be established
    await signerClient.connect(10 * 1000);

    await signerClient.generateDistributedSecret(secretId);
  } finally {
    await signerClient.disconnect();
  }
};

Important! At this stage of SDK development, it is recommended to use a similar approach when interacting with the service, i.e., connecting immediately before interaction and disconnecting afterwards. This will help to avoid common network errors until they are fully resolved.

Currency Address Synchronization

A currency address is required to receive assets and request balance information, so it is recommended to synchronize it immediately when creating a wallet.

To reduce synchronization time and improve user experience, it is recommended to use a single public key (sync parameters) for all currencies within the same cryptographic system. To do so, first synchronize one public key for the corresponding cryptographic system, and then generate desired currencies' addresses with it.

Each new synchronization procedure is bound to a unique identifier, and its results are recorded in the provided StorageDriver, which allows (with a saved syncSessionId) to synchronize the key once and then use the results permanently. However, loss of the synchronization data does not have long-term consequences, as it is possible to perform synchronization again and obtain the same public key and addresses.

The following data is required for the synchronization procedure:

  • secretId - identifier of the secret, serving as the entropy for this wallet. Secrets must have already been generated by the time of synchronization;
  • syncSessionId - synchronization session identifier. In case of a match, the previous session with such identifier will be overwritten;
  • curve - the elliptic curve. For all currently supported currencies, it is secp256k1;
  • derivationCoin - HD key derivation parameter that directly affects the address generation result. Unique values lead to the generation of unique keys. It is recommended to use a fixed value for a specific cryptographic system and vary the key value using the next parameter;
  • derivationAccount - HD key derivation parameter that directly affects the address generation result. Unique values lead to the generation of unique keys.
import { syncDistributedEddsaKey, getEddsaPublicKey } from '@spatium/sdk';

export const ensureEddsaPublicKey = async (signerClient: SignerClient, secretId: string, syncSessionId: string, derivationCoin: number, derivationAccount: number): Promise<string> => {
  const publicKey = await getEddsaPublicKey(signerClient, secretId, syncSessionId).catch(() => null);
  if (publicKey) {
    return publicKey;
  }

  try {
    // Ожидаем установки соедения 
    await signerClient.connect(10 * 1000);

    const distributedEddsaKey = await syncDistributedEddsaKey(signerClient, secretId, syncSessionId, 'secp256k1', derivationCoin, derivationAccount);
    return distributedEddsaKey
  } finally {
    await signerClient.disconnect();
  }
};

To obtain an address in a specific blockchain from a public key, it is recommended to use Blockchain Connector Service.

import axios from 'axios';
import { randomBytes, uuid } from '@spatium/sdk';

type XlmGetAddressRequest = {
  network?: 'livenet' | 'testnet';
  publicKey: string;
  prefix?: boolean;
};
type XlmGetAddressResponse = {
  requestId: string;
  data: { address: string };
}

export const xlmGetAddress = async (
  auth: AuthorizationSession,
  chain: XLMChain,
  { network, publicKey, prefix }: XlmGetAddressRequest,
): Promise<XlmGetAddressResponse['data']> => {
  const token = await auth.getPermissionToken();

  const response = await axios.post(
    `https://cloud.spatium.net/blockchain-connector-xlm/v1/api/get-address`,
    {
      publicKey,
      network,
      prefix,
    },
    {
      headers: {
        'request-id': uuid(randomBytes),
        'authorization': `Bearer ${token}`,
      },
    },
  ).then((result) => result.data);

  return response.data;
};

Important! In order to be able to restore all addresses with user funds in case of data loss in the StorageDriver, it is necessary to ensure backup of a client secret and an external storage of address generation parameters, specifically:

  • secretId - generation data, also needs to be stored along with the secret backup
  • curve - generation data
  • derivationCoin - generation data
  • derivationAccount - generation data

Retrieving Address Information

Having a synchronized address (or any other address), you can access the Address Info Service to retrieve detailed information about the address, including various assets' balances and transaction history.

import axios from 'axios';
import { randomBytes, uuid } from '@spatium/sdk';

type XlmGetAddressRequest = {
  network?: 'livenet' | 'testnet';
  address: string;
};
type XlmGetAddressResponse = {
  requestId: string;
  data: AddressInfo;
};

export const xlmGetAddressInfo = async (
  auth: AuthorizationSession,
  { network, address }: XlmGetAddressRequest,
): Promise<XlmGetAddressResponse['data']> => {
  const token = await auth.getPermissionToken();

  const result = await axios.get(
    `https://cloud.spatium.net/address-info-xlm-service/v1/api/xlm`,
    {
      params: { network, address },
      headers: {
        'request-id': uuid(randomBytes),
        'authorization': `Bearer ${token}`,
      },
    },
  ).then((result) => result.data);

  return result.data;
};

Transaction Signing

Transaction signing includes several steps:

  • Estimating a transaction fee.
  • Forming a transaction hash.
  • Signing a transaction hash.
  • Forming a signed transaction.
  • Sending the transaction to the blockchain.

Of all these stages, only the signing of the transaction hash is performed using SDK, the rest is provided through the Blockchain Connector Service API.

Getting Fee Info

To provide the correct fee size, it is useful to address current fee statistics.

Note

There are different maximum fee forming strategies. But one shound take into account, that a transaction with a low maximum fee won't be processed with a high network load, so we recommend using the statistically highest fee with the addition of a small backup - current minimal fee per operation (feeCharged.max + lastLedgerBaseFee), at the same time leaving the option to enter any fee value manually. More info about network fee you can find here.

import axios from 'axios';
import { randomBytes, uuid } from '@spatium/sdk';

type XlmGetFeeStatRequest = {
  network?: 'livenet' | 'testnet';
};

type XlmGetFeeStatResponse = {
  requestId: string;
  data: { 
    lastLedgerBaseFee: string;
    feeCharged: {
      min: string,
      max: string,
    } 
  };
};

export const xlmGetFeeStat = async (
  auth: AuthorizationSession,
  { network }: XlmGetFeeStatRequest
): Promise<XlmGetFeeStatResponse['data']> => {
  const token = await auth.getPermissionToken();

  const response = await axios.get(
    `https://cloud.spatium.net/blockchain-connector-xlm/v1/api/prepare-transaction/fee-stat/xlm`,
    {
      params: { network },
      headers: {
        'request-id': uuid(randomBytes),
        'authorization': `Bearer ${token}`,
      },
    },
  ).then((result) => result.data);

  return response.data;
};

Transaction hash

With all the preliminary data, it is possible to form the hash for signing.

In XLM blockchain getting hash depends on transaction type:

  • Transfer
  • Adding trustline
  • Claim

Getting Transaction Hash for Transfer

Important

According to Stellar logic, one can't transfer XLM to a non-existent account (it is necessary to create one first). This endpoint will automatically create the account if it's necessary, but there will be no notice about account absence! More info about getting a transaction hash for transfer is here.

import axios from 'axios';
import { randomBytes, uuid } from '@spatium/sdk';

type XlmGetHashTransferRequest = {
  network?: 'livenet' | 'testnet';
  publicKey: string;
  to: string,
  amount: string,
  asset?: StellarAsset;
  fee: string;
  memo?: string;
 };

type XlmGetHashTransferResponse = {
  requestId: string;
  data: {
    unsignedMessage: string;
    hash: string;
  }
};

export const xlmGetHashTransfer = async (
  auth: AuthorizationSession,
  { network, publicKey, to, amount, asset, fee, memo }: XlmGetHashTransferRequest,
): Promise<XlmGetHashTransferResponse> => {
  const token = await auth.getPermissionToken();

  const response = await axios.post(
    'https://cloud.spatium.net/blockchain-connector-xlm/v1/api/transaction/get-hash/xlm/transfer',
    {
      network,
      publicKey,
      to,
      amount,
      asset,
      fee,
      memo,
    },
    {
      headers: {
        'request-id': uuid(randomBytes),
        'authorization': `Bearer ${token}`,
      },
    },
  ).then((result) => result.data);

  return response.data;
};

Getting Transaction Hash for Trustline Adding

import axios from 'axios';
import { randomBytes, uuid } from '@spatium/sdk';

type XlmGetHashAddTrustlineRequest = {
  network?: 'livenet' | 'testnet';
  publicKey: string;
  to: string,
  amount?: string,
  asset: StellarAsset;
  fee: string;
  memo?: string;
 };

type XlmGetHashAddTrustlineResponse = {
  requestId: string;
  data: {
    unsignedMessage: string;
    hash: string;
  }
};

export const xlmGetHashAddTrustline = async (
  auth: AuthorizationSession,
  { network, publicKey, to, amount, asset, fee, memo }: XlmGetHashAddTrustlineRequest,
): Promise<XlmGetHashAddTrustlineResponse> => {
  const token = await auth.getPermissionToken();

  const response = await axios.post(
    'https://cloud.spatium.net/blockchain-connector-xlm/v1/api/transaction/get-hash/xlm/add-trustline',
    {
      network,
      publicKey,
      to,
      amount,
      asset,
      fee,
      memo,
    },
    {
      headers: {
        'request-id': uuid(randomBytes),
        'authorization': `Bearer ${token}`,
      },
    },
  ).then((result) => result.data);

  return response.data;
};

Getting Transaction Hash for Claim

import axios from 'axios';
import { randomBytes, uuid } from '@spatium/sdk';

type XlmGetHashClaimRequest = {
  network?: 'livenet' | 'testnet';
  publicKey: string;
  claimableBalanceId: string,
  fee: string;
  memo?: string;
 };

type XlmGetHashClaimResponse = {
  requestId: string;
  data: {
    unsignedMessage: string;
    hash: string;
  }
};

export const xlmGetHashClaim = async (
  auth: AuthorizationSession,
  { network, publicKey, claimableBalanceId, fee, memo }: XlmGetHashClaimRequest,
): Promise<XlmGetHashClaimResponse> => {
  const token = await auth.getPermissionToken();

  const response = await axios.post(
    'https://cloud.spatium.net/blockchain-connector-xlm/v1/api/transaction/get-hash/xlm/claim',
    {
      network,
      publicKey,
      claimableBalanceId,
      fee,
      memo,
    },
    {
      headers: {
        'request-id': uuid(randomBytes),
        'authorization': `Bearer ${token}`,
      },
    },
  ).then((result) => result.data);

  return response.data;
};

SMPC Signing of the Hash

import { signEddsaMessage } from '@spatium/sdk';
import { randomBytes, uuid } from '@spatium/sdk';

export const signEddsa = async (signerClient: SignerClient, secretId: string, syncSessionId: string, message: string): Promise<EddsaSignature> => {
  const signSessionId = uuid(randomBytes);

  try {
    // Wait for the actual connection to be established
    await signerClient.connect(10 * 1000);

    return await signerClient.signEddsaMessage(secretId, syncSessionId, signSessionId, message);
  } finally {
    await signerClient.disconnect();
  }
};

Forming the Signed Transaction

A signature needs to be attached to the transaction, thereby obtaining data ready to be sent to the blockchain.

import axios from 'axios';
import { randomBytes, uuid } from '@spatium/sdk';

type XlmAttachSignatureRequest = {
  network?: 'livenet' | 'testnet';
  publicKey: string;
  unsignedMessage: string;
  signature: EddsaSignature,
};

type XlmAttachSignatureResponse = {
  requestId: string;
  data: { txdata: string };
};

export const xlmAttachSignature = async (
  auth: AuthorizationSession,
  { network, publicKey, unsignedMessage, signature }: XlmAttachSignatureRequest,
): Promise<XlmAttachSignatureResponse['data']> => {

  const response = await axios.post(
    `https://cloud.spatium.net/blockchain-connector-xlm/v1/api/transaction/attach-signature/xlm`,
    {
      network,
      publicKey,
      unsignedMessage,
      signature,
    },
    {
      headers: {
        'request-id': uuid(randomBytes),
        'authorization': `Bearer ${token}`,
      },
    },
  ).then((result) => result.data);

  return response.data;
};

Sending a Transaction to the Network

Blockchain Connector Service is also responsible for sending transactions to a blockchain.

import axios from 'axios';
import { randomBytes, uuid } from '@spatium/sdk';

type XlmSendTXRequest = {
  txdata: string;
};
type XlmSendTXResponse = {
  requestId: string;
  data: { txid: string };
};

export const xlmSendTX = async (
  auth: AuthorizationSession,
  { txdata }: XlmSendTXRequest,
): Promise<XlmSendTXResponse['data']> => {
  const token = await auth.getPermissionToken();

  const response = await axios.post(
    `https://cloud.spatium.net/blockchain-connector-xlm/v1/api/transaction/send/xlm`,
    {
      network,
    },
    {
      headers: {
        'request-id': uuid(randomBytes),
        'authorization': `Bearer ${token}`,
      },
    }
  ).then((result) => result.data);

  return response.data;
};

Complete Procedure

import { AuthorizationSession, SignerClient } from '@spatium/signer-client';
import { randomBytes, uuid } from '@spatium/sdk';

const auth = new AuthorizationSession('https://cloud.spatium.net/authorization/v1', uuid(randomBytes), ['read', 'secret']);

// получение security токенов
const { data: { securityToken } } = await axios.post('https://cloud.spatium.net/authorization/v1/api/security-factor/credentials', {
    username: 'username', password: 'password',
  }, {
    headers: {
      'request-id': uuid(randomBytes),
    },
  }).then(({ data }) => data);

await auth.establish([securityToken]);

const etcLikeSignTransaction = async (auth: AuthorizationSession, signerClient: SignerClient, syncSessionId: string, publicKey: string, to: string, amount: string) => {

  const { address } = await xlmGetAddress(auth, { publicKey })

  const { feeCharged } = await xlmGetFeeStat(auth, {});
  const fee = feeCharged.max;

  // getting transfer transaction hash
  const { hash, unsignedMessage } = await xlmGetHashTransfer(auth, { publicKey, to, amount, fee });

  // getting add trustline transaction hash
  const { hash, unsignedMessage } = await xlmGetHashAddTrustline(auth, { publicKey, asset, fee });

  // getting claim transaction hash
  const { hash, unsignedMessage } = await xlmGetHashClaim(auth, { publicKey, claimableBalanceId, fee });

  const signature = await signEddsa(signerClient, secretId, syncSessionId, hash);

  const { txdata } = await xlmAttachSignature(auth, { publicKey, unsignedMessage, signature });

  const { txid } = await xlmSendTX(auth, { txdata });

  return txid;
}