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

Self-Custody Use Case (BTC-like)

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 { uuid, randomBytes, MemoryStorageDriver, SpatiumCrypto } from '@spatium/sdk';
import { AuthorizationSession, ServiceStorage, SignerClient } from '@spatium/signer-client';

export const createSignerClient = () => {
  const auth = new AuthorizationSession('https://cloud.spatium.net/authorization/v1', uuid(randomBytes), ['read', 'secret']);
  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 storage, which stores both secrets at Spatium. Using 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.

Synchronizing Currency Addresses

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 the 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 { syncDistributedEcdsaKey, getEcdsaPublicKey } from '@spatium/sdk';

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

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

    const distributedEcdsaKey = await syncDistributedEcdsaKey(signerClient, secretId, syncSessionId, 'secp256k1', derivationCoin, derivationAccount);
    return distributedEcdsaKey
  } 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 BtcLikeGetAddressRequest = {
  network?: 'livenet' | 'testnet';
  publicKey: string;
  type?: 'p2pkh' | 'p2wpkh';
  prefix?: boolean;
};
type BtcLikeGetAddressResponse = {
  requestId: string;
  data: { address: string };
};

export const btcLikeGetAddress = async (
  auth: AuthorizationSession,
  chain: BTCLikeChain,
  { network, publicKey, type, prefix }: BtcLikeGetAddressRequest,
): Promise<BtcLikeGetAddressResponse['data']> => {
  const token = await auth.getPermissionToken();

  const response = await axios.post(
    `https://cloud.spatium.net/blockchain-connector-btc-like/v1/api/get-address/${chain}`,
    {
      publicKey,
      network,
      type,
      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 AddressInfo = {
  address: string;
  chain: string;
  balances: [
    {
      asset: { chain: string, kind: string },
      balance: { amount: string, decimals: number }  
    }
  ];
  transactions: [];
}
type BtcLikeGetAddressInfoRequest = {
  network?: 'livenet' | 'testnet';
  address: string;
};
type BtcLikeGetAddressInfoResponse = {
  requestId: string;
  data: AddressInfo;
};

export const btcLikeGetAddressInfo = async (
  auth: AuthorizationSession,
  chain: BTCLikeChain,
  { network, address }: BtcLikeGetAddressInfoRequest,
): Promise<BtcLikeGetAddressInfoResponse['data']> => {
  const token = await auth.getPermissionToken();

  const result = await axios.get(
    `https://cloud.spatium.net/address-info-btc-like/v1/api/${chain}`,
    {
      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:

  • Gathering current data from a blockchain, such as UTXO or nonce.
  • Estimating a transaction fee.
  • Generating a transaction hash.
  • Signing a transaction hash.
  • Creating a signed transaction.
  • Sending the transaction to the blockchain.

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

UTXO Gathering

Bitcoin-like currencies require up-to-date Unspent Transaction Outputs (UTXO) for transaction formation.

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

type BtcLikeGetUTXORequest = {
  network?: 'livenet' | 'testnet';
  address: string;
};
type UTXO = {
  txid: string;
  vout: number;
  value: string;
};
type BtcLikeGetUTXOResponse = {
  requestId: string;
  data: { utxo: UTXO[] };
};

export const btcLikeGetUTXO = async (
  auth: AuthorizationSession,
  chain: BTCLikeChain,
  { network, address }: BtcLikeGetUTXORequest,
): Promise<BtcLikeGetUTXOResponse['data']> => {
  const token = await auth.getPermissionToken();

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

  return response.data;
};

Transaction Size Estimation

To estimate the transaction fee in Bitcoin-like blockchains, the transaction size in bytes is used, which requires knowledge of UTXO as well.

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

type BtcLikeGetTXSizeRequest = {
  network?: 'livenet' | 'testnet';
  publicKey: string;
  type?: 'p2pkh' | 'p2wpkh';
  utxo: { txid: string; vout: number; value: string }[];
  to: string;
  amount: string;
};
type BtcLikeGetTXSizeResponse = { 
  requestId: string;
  data: { size: number };
};

export const btcLikeGetTXSize = async (
  auth: AuthorizationSession,
  chain: BTCLikeChain,
  { network, publicKey, type, utxo, to, amount }: BtcLikeGetTXSizeRequest,
): Promise<BtcLikeGetTXSizeResponse['data']> => {
  const token = await auth.getPermissionToken();

  const response = await axios.post(
    `https://cloud.spatium.net/blockchain-connector-btc-like/v1/api/prepare-transaction/size/${chain}`,
    {
      publicKey,
      network,
      type,
      utxo,
      to,
      amount,
    },
    {
      headers: {
        'request-id': uuid(randomBytes),
        'authorization': `Bearer ${token}`,
      },
    },
  ).then((result) => result.data);

  return response.data;
};

Getting Information about an Average Network Commission

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

type BtcLikeGetBytePricesRequest = {
  network?: 'livenet' | 'testnet';
};
type BtcLikeGetBytePricesResponse = {
  data: {[key: string] : {
    date: number,
    feeInfo: {
      fast: string,
      normal: string,
      slow: string,
    }
  }}
}

export const btcLikeGetBytePrices = async (
  auth: AuthorizationSession,
  { network }: BtcLikeGetBytePricesRequest,
): Promise<BtcLikeGetBytePricesResponse['data']> => {

  const token = await auth.getPermissionToken();

  const response = await axios.get(
    `https://cloud.spatium.net/fee-info-btc-like/v1/static/fee-info-${network}.json`, {
      params: { network },
      headers: {
        'request-id': uuid(randomBytes),
        'authorization': `Bearer ${token}`,
      },
    },
  ).then((result) => result.data);

  return response;
};

Calculating Transaction Fee

The final value of the optimal fee is determined by the transaction size and the average cost per byte. Additionally, you can manually input the total fee amount, disregarding both the size and estimation.

const fee = (Number(prices.normal) * size).toFixed();

<!-- ### General Transaction Estimation Request There is a single endpoint for obtaining a transaction estimate, which executes:

  • Get UTXO;
  • Transaction size estimation;
  • Getting information about the average network commission;
  • Calculating transaction tee.
import axios from 'axios';
import { randomBytes, uuid } from '@spatium/sdk';

type BtcLikeGetTxEstimateRequest = {
  address: string;
  network?: 'livenet' | 'testnet';
  publicKey: string;
  type?: 'p2pkh' | 'p2wpkh';
  to: string;
  amount: string;
}
type BtcLikeGetTxEstimateResponse = {
  requestId: string;
  data: {
    utxo: UTXO[];
    size: number;
    fees: { normal: string; fast: string; slow: string };
  };
};

export const btcLikeGetTXEstimate = async  (
  auth: AuthorizationSession,
  chain: BTCLikeChain,
  { address, network, publicKey, type, to, amount }: BtcLikeGetTxEstimateRequest,
): Promise<BtcLikeGetTxEstimateResponse['data']> => {
  const token = await auth.getPermissionToken();

  const response = await axios.post(
    `https://cloud.spatium.net/blockchain-connector-btc-like/v1/api/prepare-transaction/estimate/${chain}`,
    {
      address,
      network,
      publicKey,
      type,
      to,
      amount,
    },
    {
      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 a signing hash (in this case, a set of hashes).

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

type BtcLikeGetHashRequest = {
  network?: 'livenet' | 'testnet';
  publicKey: string;
  type?: 'p2pkh' | 'p2wpkh';
  utxo: { txid: string; vout: number; value: string }[];
  to: string;
  amount: string;
  fee: string;
};
type BtcLikeGetHashResponse = {
  requestId: string;
  data: {
    inputIndex: number;
    hash: string;
  }[];
};

export const btcLikeGetHash = async (
  auth: AuthorizationSession,
  chain: BTCLikeChain,
  { network, publicKey, type, utxo, to, amount, fee }: BtcLikeGetHashRequest,
): Promise<BtcLikeGetHashResponse['data']> => {
  const token = await auth.getPermissionToken();

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

  return response.data;
};

SMPC Hash Signature

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

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

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

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

Forming a Signed Transaction

A signature (in this case, a set of signatures) needs to be attached to a transaction, thereby obtaining data ready to be sent to the blockchain.

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

type BtcLikeAttachSignatureRequest = {
  network?: 'livenet' | 'testnet';
  publicKey: string;
  type?: 'p2pkh' | 'p2wpkh';
  utxo: { txid: string; vout: number; value: string }[];
  to: string;
  amount: string;
  fee: string;
  signatures: { inputIndex: number; signature: EcdsaSignature }[];
};
type BtcLikeAttachSignatureResponse = {
  requestId: string;
  data: { txdata: string };
};

export const btcLikeAttachSignature = async (
  auth: AuthorizationSession,
  chain: BTCLikeChain,
  { network, publicKey, type, utxo, to, amount, fee, signatures }: BtcLikeAttachSignatureRequest,
): Promise<BtcLikeAttachSignatureResponse['data']> => {
  const token = await auth.getPermissionToken();

  const response = await axios.post(
    `https://cloud.spatium.net/blockchain-connector-btc-like/v1/api/transaction/attach-signature/${chain}`,
    {
      publicKey,
      network,
      type,
      utxo,
      to,
      amount,
      fee,
      signatures,
    },
    {
      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 the transaction to a blockchain

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

type BtcLikeSendTXRequest = {
  network?: 'livenet' | 'testnet';
  txdata: string;
};
type BtcLikeSendTXResponse = {
  requestId: string;
  data: { txid: string };
};

export const btcLikeSendTX = async (
  auth: AuthorizationSession,
  chain: BTCLikeChain,
  { network, txdata }: BtcLikeSendTXRequest,
): Promise<BtcLikeSendTXResponse> => {
  const token = await auth.getPermissionToken();

  const response = await axios.post(
    `https://cloud.spatium.net/blockchain-connector-btc-like/v1/api/transaction/send/${chain}`,
    {
      network,
      txdata,
    },
    {
      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']);

// get security tokens
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 btcLikeSignTransaction = async (auth: AuthorizationSession, signerClient: SignerClient, syncSessionId: string, 
  chain: BTCLikeChain, publicKey: string, to: string, amount: string) => {

  const { address } = await btcLikeGetAddress(auth, 'btc', { publicKey });

  const { utxo } = await btcLikeGetUTXO(auth, 'btc', { address });

  const { size } = await btcLikeGetTXSize(auth, 'btc', { publicKey, utxo, to, amount });

  const pricePerByte = await btcLikeGetBytePrices(auth, {});

  const fee = (Number(pricePerByte.btc?.feeInfo.normal) * size).toFixed();

  const { hashes } = await btcLikeGetHash(auth, 'btc', { publicKey, utxo, to, amount, fee });

  const signatures: { inputIndex: number; signature: EcdsaSignature }[] = [];

  for (const { inputIndex, hash } of hashes) {
    const signature = await signEcdsa(signerClient, syncSessionId, hash);

    signatures.push({ inputIndex, signature });
  }

  const txdata = await btcLikeAttachSignature(auth, 'btc', { publicKey, utxo, to, amount, fee, signatures });

  const txid = await btcLikeSendTX(auth, 'btc', { txdata });

  return txid;
}