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

Self-Custody Use Case (ETH-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 { 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 { 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 {
    // Ожидаем установки соедения 
    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 EthLikeGetAddressRequest = {
  network?: 'livenet' | 'testnet';
  publicKey: string;
  prefix?: boolean;
};
type EthLikeGetAddressResponse = {
  requestId: string;
  data: { address: string };
}

export const ethLikeGetAddress = async (
  auth: AuthorizationSession,
  chain: ETHLikeChain,
  { network, publicKey, prefix }: EthLikeGetAddressRequest,
): Promise<EthLikeGetAddressResponse['data']> => {
  const token = await auth.getPermissionToken();

  const response = await axios.post(
    `https://cloud.spatium.net/blockchain-connector-eth-like/v1/api/get-address/${chain}`,
    {
      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 EthLikeGetAddressRequest = {
  network?: 'livenet' | 'testnet';
  address: string;
};
type EthLikeGetAddressResponse = {
  requestId: string;
  data: AddressInfo;
};

export const ethLikeGetAddressInfo = async (
  auth: AuthorizationSession,
  chain: ETHLikeChain,
  { network, address }: EthLikeGetAddressRequest,
): Promise<EthLikeGetAddressResponse['data']> => {
  const token = await auth.getPermissionToken();

  const result = await axios.get(
    `https://cloud.spatium.net/address-info-eth-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.
  • 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.

Gathering Nonce

Ethereum-like currencies require a current nonce (a one-time transaction number) to form a transaction.

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

type EthLikeGetNonceRequest = {
  network?: 'livenet' | 'testnet';
  address: string;
};
type EthLikeGetNonceResponse = {
  requestId: string;
  data: { nonce: number };
};

export const ethLikeGetNonce = async (
  auth: AuthorizationSession,
  chain: ETHLikeChain,
  { network, address }: EthLikeGetNonceRequest
): Promise<EthLikeGetNonceResponse['data']> => {
  const token = await auth.getPermissionToken();

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

  return response.data;
};

Gathering ERC-20 Token Transfer Data

Important! This method is only used when sending ERC-20 tokens, and when sending the native currency of the blockchain, this method is not used, and an empty string is sent in the data parameter of subsequent requests for working with the transaction.

To send ERC-20 tokens, it is necessary to obtain corresponding transfer data, this data is passed in the data field of subsequent requests for working with the transaction.

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

type GetErc20TransferDataRequest = {
  to: string;
  amount: string;
};
type GetErc20TransferDataResponse = {
  requestId: string;
  data: { erc20TransferData: string };
};

export const getErc20TransferData = async (
  auth: AuthorizationSession,
  { to, amount }: GetErc20TransferDataRequest
): Promise<GetErc20TransferDataResponse['data']> => {
  const token = await auth.getPermissionToken();

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

  return response.data;
};

Estimating the Workload for Transaction Processing

In Ethereum-like blockchains, the workload performed by the validator for transaction processing is used to estimate the transaction fee, for which it is also necessary to know the nonce.

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

type EthLikeGetGasLimitRequest = {
  network?: 'livenet' | 'testnet';
  to: string;
  amount: string;
  data: string;
  nonce: number;
};
type EthLikeGetGasLimitResponse = {
  requestId: string;
  data: { gasLimit: string };
};

export const ethLikeGetGasLimit = async (
  auth: AuthorizationSession,
  chain: ETHLikeChain,
  { network, to, amount, data, nonce }: EthLikeGetGasLimitRequest
): Promise<EthLikeGetGasLimitResponse['data']> => {
  const token = await auth.getPermissionToken();

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

  return response.data;
};

Obtaining Information on the Average Network Fee

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

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

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

  const token = await auth.getPermissionToken();

  const response = await axios.get(
    `https://cloud.spatium.net/fee-info-eth-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 amount of an optimal fee is formed from the workload performed by the validator for transaction processing and the average cost of one unit of work.

const fee = (Number(gasPrices.normal) * gasLimit).toFixed();

However, within the API, calculating this value is not required, as the gasLimit and gasPrice transaction parameters are passed directly.

<!-- ### General Transaction Estimation Request

There is also a single endpoint for obtaining a transaction estimate, which executes:

  • Gathering nonce;
  • Estimating the workload for transaction processing;
  • Obtaining information on the average network fee.
import axios from 'axios';
import { randomBytes, uuid } from '@spatium/sdk';

type EthLikeGetTxEstimateRequest = {
  address: string;
  network?: 'livenet' | 'testnet';
  data: string;
  to: string;
  amount: string;
}
type EthLikeGetTxEstimateResponse = {
  requestId: string;
  data: {
    nonce: number;
    gasLimit: string;
    gasPrices: { normal: string; fast: string; slow: string };
  };
};

export const ethLikeGetTXEstimate = async  (
  auth: AuthorizationSession,
  chain: ETHLikeChain,
  { address, network, data, to, amount }: EthLikeGetTxEstimateRequest,
): Promise<EthLikeGetTxEstimateResponse['data']> => {
  const token = await auth.getPermissionToken();

  const response = await axios.post(
    `https://cloud.spatium.net/blockchain-connector-eth-like/v1/api/prepare-transaction/estimate/${chain}`,
    {
      address,
      network,
      data,
      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 the hash for signing.

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

type EthLikeGetHashRequest = {
  network?: 'livenet' | 'testnet';
  publicKey: string;
  to: string;
  amount: string;
  data: string;
  nonce: number;
  gasLimit: string;
  gasPrice: string;
};
type EthLikeGetHashResponse = {
  requestId: string;
  data: { hash: string };
};

export const ethLikeGetHash = async (
  auth: AuthorizationSession,
  chain: ETHLikeChain,
  { network, publicKey, to, amount, data, nonce, gasLimit, gasPrice }: EthLikeGetHashRequest,
): Promise<EthLikeGetHashResponse['data']> => {
  const token = await auth.getPermissionToken();

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

  return response.data;
};

SMPC Signing of the Hash

import { signEcdsaMessage } from '@spatium/sdk';
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 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 EthLikeAttachSignatureRequest = {
  network?: 'livenet' | 'testnet';
  publicKey: string;
  to: string;
  amount: string;
  data: string;
  nonce: number;
  gasLimit: string;
  gasPrice: string;
  signature: EcdsaSignature;
};
type EthLikeAttachSignatureResponse = {
  requestId: string;
  data: { txdata: string };
};

export const ethLikeAttachSignature = async (
  auth: AuthorizationSession,
  chain: ETHLikeChain,
  { network, publicKey, to, amount, data, nonce, gasLimit, gasPrice, signature }: EthLikeAttachSignatureRequest,
): Promise<EthLikeAttachSignatureResponse['data']> => {
  const token = await auth.getPermissionToken();

  const response = await axios.post(
    `https://cloud.spatium.net/blockchain-connector-eth-like/v1/api/transaction/attach-signature/${chain}`,
    {
      network,
      publicKey,
      to,
      amount,
      data,
      nonce,
      gasLimit,
      gasPrice,
      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 EthLikeSendTXRequest = {
  network?: 'livenet' | 'testnet';
  txdata: string;
};
type EthLikeSendTXResponse = {
  requestId: string;
  data: { txid: string };
};

export const ethLikeSendTX = async (
  auth: AuthorizationSession,
  chain: ETHLikeChain,
  { network, txdata }: EthLikeSendTXRequest,
): Promise<EthLikeSendTXResponse['data']> => {
  const token = await auth.getPermissionToken();

  const response = await axios.post(
    `https://cloud.spatium.net/blockchain-connector-eth-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 etcLikeSignTransaction = async (auth: AuthorizationSession, signerClient: SignerClient, syncSessionId: string, 
  chain: ETHLikeChain, publicKey: string, to: string, amount: string) => {
  const { nonce } = await ethLikeGetNonce(auth, 'eth', { address });

  const { gasLimit } = await ethLikeGetGasLimit(auth, 'eth', { to, amount, data: '', nonce });

  const { gasPrices } = await ethLikeGetGasPrices(auth, 'eth', {});

  const { hash } = await ethLikeGetHash(auth, 'eth', { publicKey, to, amount, data: '', nonce, gasLimit, gasPrice: gasPrices.normal });

  const signature = await signEcdsa(signerClient, syncSessionId, hash);

  const { txdata } = await ethLikeAttachSignature(auth, 'eth', { publicKey, to, amount, data: '', nonce, gasLimit, gasPrice: gasPrices.normal, signature });

  const { txid } = await ethLikeSendTX(auth, 'eth', { txdata });

  return txid;
}