pendulum-chain / substrate-stellar-sdk

A Rust SDK for Stellar that can be used for Substrate projects
Apache License 2.0
11 stars 11 forks source link

A Stellar SDK for Substrate projects

This is an SDK for Stellar that is suitable to be used in a Substrate project. It does not depend on the standard library but on the crate sp-std, which is Substrate's replacement of Rust's standard library.

Crate Features

This crate has three features:

Conversion traits

In order to make the SDK API convenient to use with a variety of input types, we make heavy use of conversion traits. For example the type Horizon implements the method fetch_account whose first parameter is an account id. This parameter can be provided as a string representing the string encoding of the account id:

horizon.fetch_account("GDGRDTRINPF66FNC47H22NY6BNWMCD5Q4XZTVA2KG7PFZ64WHRIU62TQ", 1000)?;

Since strings in Substrate are usually represented as Vec<u8>, also a vector representation of this string can be used as an argument:

let vec: Vec<u8> = Vec::from("GDGRDTRINPF66FNC47H22NY6BNWMCD5Q4XZTVA2KG7PFZ64WHRIU62TQ".as_bytes());
horizon.fetch_account(vec, 1000)?;

Also u8 slices and u8 arrays are possible argument types:

let slice: &[u8] = "GDGRDTRINPF66FNC47H22NY6BNWMCD5Q4XZTVA2KG7PFZ64WHRIU62TQ".as_bytes();
let array: [u8; 56] = slice.try_into()?;
horizon.fetch_account(slice, 1000)?;
horizon.fetch_account(array, 1000)?;

It is also possible to provide an AccountId struct itself:

let account_id = AccountId::from_encoding("GDGRDTRINPF66FNC47H22NY6BNWMCD5Q4XZTVA2KG7PFZ64WHRIU62TQ")?;
horizon.fetch_account(account_id, 1000)?;

This crate provides the following conversion traits:

IntoAccountId

This is the trait for parameters that represent an AccountId. It is implemented by

IntoAmount

This is the trait for parameters that represent an asset amount. This is used to cleanly distinguish between stroop amounts and lumen amounts (where one lumen is 10_000_000 stroops). It is implemented by

It is recommended to use either LumenAmount or the string representation as they can be converted without loss to Stellar's internal stroop representation of amounts.

IntoClaimbleBalanceId

This is the trait for parameters that represent an ClaimableBalanceId. It is implemented by

IntoDataValue

This is the trait for parameters that represent an DataValue. It is implemented by

IntoHash

This is the trait for parameters that represent an Hash. It is implemented by

IntoMuxedAccountId

This is the trait for parameters that represent a MuxedAccount. Be aware that the type MuxedAccount contains simple account ids as well as proper multiplexed account ids. It is implemented by

IntoPublicKey

This is the trait for parameters that represent a PublicKey. Be aware that the types AccountId and PublicKey are aliases (they are synonyms in Stellar). The trait IntoPublicKey exists for convenience and to make it more clear when an account id is used as a public key. It is implemented by

IntoSecretKey

This is the trait for parameters that represent a SecretKey. It is implemented by

IntoTimePoint

This is the trait for parameters that represent a point in time used by transaction time bounds. It is implemented by

Create, Sign and Submit Transactions

This is one of the main workflows when using this SDK. Note that these features only become available when using the crate feature offchain. It usually consists of the following steps:

  1. Create an instance of the Horizon type and provide the base url of the horizon server.
  2. Fetch the next sequence number of the transaction's source account from the horizon server. The next sequence number is one higher than the current sequence number of the account and must be used as the transaction sequence number in order to be valid.
  3. Build the transaction and provide
    • The source account id
    • The fetched sequence number
    • The fees per operation
    • The timebounds (optional)
    • The memo (optional)
  4. Append operations to the transaction. The transaction needs to be mutable. Each operation has constructor methods such as Operation::new_payment (for a payment operation) or Operation::new_bump_sequence (for a bump sequence number operation). The constructors make use of the conversion traits. Note that one needs to chain the method call set_source_account if one wants to set a dedicated source account for an operation.
  5. Convert the transaction into a transaction envelope. This will create an envelope without signatures. Note that this operation mutates the fee of the transaction and multiplies the fee per operation (provided when building the transaction) with the number of appended operations. The transaction in the transaction envelope should not be mutated anymore after this step, otherwise the signatures added subsequently will not be valid anymore.
  6. Sign the transaction envelope with the required secret keys. Signatures are only valid for certain Stellar networks passphrases (so that a transaction can be signed either for the public network or the test network). For that reason the method for signing a transaction requires a netwok passphrase.
  7. Submit the signed envelope to the Stellar network using the Horizon API.

The following code shows a complete example.

use substrate_stellar_sdk::{
    horizon::Horizon, network::TEST_NETWORK, Asset, IntoSecretKey, Memo, MilliSecondEpochTime,
    MuxedAccount, Operation, Price, PublicKey as StellarPublicKey, SecondEpochTime, StroopAmount,
    TimeBounds, Transaction, TransactionEnvelope, XdrCodec,
};

// ...
// in some function:

const ACCOUNT_ID1: &str = "GDGRDTRINPF66FNC47H22NY6BNWMCD5Q4XZTVA2KG7PFZ64WHRIU62TQ";
const ACCOUNT_ID2: &str = "GBNKQVTFRP25TIQRODMU5GJGSXDKHCEUDN7LNMOS5PNM427LMR77NV4M";
const ACCOUNT_ID3: &str = "GCACWDM2VEYTXGUI3CUYLBJ453IBEPQ3XEJKA772ARAP5XDQ4NMGFZGJ";

const SIGNER1: &str = "SCVKZEONBSU3XD6OTHXGAP6BTEWHOU4RPZQZJJ5AVAGPXUZ5A4D7MU6S";
const SIGNER3: &str = "SDOKV37I4TI655LMEMDQFOWESJ3LK6DDFKIVTYKN4YYTSAYFIBPP7MYI";

// Step 1: instantiate horizon server
let horizon = Horizon::new("https://horizon-testnet.stellar.org");

// Step 2: fetch next sequence number of account
let next_sequence_number = horizon.fetch_next_sequence_number(ACCOUNT_ID1, 10_000)?;

debug::info!("Sequence number: {}", next_sequence_number);

// Step 3: build transaction
let mut transaction = Transaction::new(
    ACCOUNT_ID1,
    next_sequence_number,
    Some(321),
    Some(TimeBounds::from_time_points(
        SecondEpochTime(162620000),
        MilliSecondEpochTime(1_667_257_200_000),
    )),
    Some(Memo::from_text_memo("Hello World!")?),
)?;

// Step 4: add operations
transaction.append_operation(
    Operation::new_payment(
        ACCOUNT_ID2,
        Asset::from_asset_code("USD", ACCOUNT_ID3)?,
        StroopAmount(1_234_560_000),
    )?
    .set_source_account(ACCOUNT_ID3)?,
)?;

transaction.append_operation(Operation::new_manage_sell_offer(
    Asset::from_asset_code("DOMINATION", ACCOUNT_ID2)?,
    Asset::native(),
    "152.103",
    Price::from_float(4.58)?,
    Some(1742764),
)?)?;

// Step 5: transform into transaction envelope and sign
let mut envelope = transaction.into_transaction_envelope();

// Step 6: sign transaction envelope
envelope.sign(
    &TEST_NETWORK,
    vec![&SIGNER1.into_secret_key()?, &SIGNER3.into_secret_key()?],
)?;

// Step 7: submit transaction
let submission_response = horizon.submit_transaction(&envelope, 60_000, true);
debug::info!("Response: {:?}", submission_response);

Stellar XDR Types

Stellar defines a bunch of data types on a protocol level. These types are serialized and deserialized using the XDR standard.

This crates contains all these Stellar defined types (in substrate_stellar_sdk::types) including a complete XDR encoder and decoder for these types. For that purpose every type implements the trait XdrCodec, which provides the following methods:

Autogenerator

The types and the XDR decoder are automatically generated via the tool in /autogenerator. This generator will download the latest Stellar types from the Stellar Core GitHub repository and will generate the types and XDR decoder.

Crate Feature all-types

By default not all Stellar types will be generated. Missing types are special types that are only used internally for the consensus mechanism. In order to generate all types, use the feature flag all-types.