How to use stellar-sdk - 10 common examples

To help you get started, we’ve selected a few stellar-sdk examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github chatch / xcat / integration-test / protocol-xlm-eth-scenario-1.js View on Github external
*
 * Runs against local Stellar and Ethereum nodes both of which need to be started
 * before the script is run.
 */

/*
 * Ethereum Accounts
 */
const web3 = new Web3(new Web3.providers.HttpProvider())
const eSellerAddr = web3.eth.accounts[4]
const eBuyerAddr = web3.eth.accounts[5]

/*
 * Stellar Accounts
 */
const sSellerKP = sdk.Keypair.random()
const sBuyerKP = sdk.Keypair.random()

/*
 * Hashlock preimage and hash for the trade
 */
const {secret: preImageStr, hash: hashXStr} = newSecretHashPair()

/*
 * Trade definition
 */
const initialTrade = {
  initialSide: Protocol.TradeSide.STELLAR,
  timelock: Date.now() + 120,
  commitment: hashXStr.substring(2), // slice off prefix '0x'
  stellar: {
    token: 'XLM',
github irisli / bookmaker / deleteAllOffers.js View on Github external
module.exports = async function deleteAllOffers(Server, account, keypair) {
  // Get the offer IDs
  const offersForTarget = await Server.offers('accounts', keypair.accountId())
    .order('asc')
    .limit(20)
    .call();

  if (offersForTarget.records.length === 0) {
    return 0;
  }

  let transaction = new StellarSdk.TransactionBuilder(account);
  console.log(`Deleting ${offersForTarget.records.length} offers for ${keypair.accountId()}`);
  offersForTarget.records.forEach((record) => {
    const offerId = record.id;
    transaction = transaction.addOperation(StellarSdk.Operation.manageOffer({
      // It doesn't matter who the issuer is since this is just going to get deleted
      buying: StellarSdk.Asset.native(),
      selling: new StellarSdk.Asset('0000', account.accountId()),
      amount: '0',
      price: '1',
      offerId,
    }));
  });

  // transaction = transaction.addMemo(StellarSdk.Memo.text(`bookmaker ${version}`));
  transaction = transaction.build();
github Block-Equity / desktop-wallet / app / services / networking / horizon.js View on Github external
export const sendPayment = ({ publicKey, decryptSK, sequence, destinationId, amount, memoValue, issuerPK, assetType }) => {
  let sourceKeys = StellarSdk.Keypair.fromSecret(decryptSK)
  let transaction
  var blockEQToken = new StellarSdk.Asset(assetType, issuerPK)
  const isMemoText = () => {
    return /[a-z]/i.test(memoValue)
  }
  var memoParam
  if (memoValue.length > 0) {
    memoParam = isMemoText() ? StellarSdk.Memo.text(memoValue.toString()) : StellarSdk.Memo.id(memoValue.toString())
  }

  return new Promise((resolve, reject) => {
    server.loadAccount(destinationId)
      // If the account is not found, then create a transaction for creating an account
      .catch(error => {
        console.log(error.name)
        if (error.name === 'NotFoundError') {
          resolve({
            exists: false,
            payload: error
          })
        }
      })
      // If there was no error, load up-to-date information on your account.
      .then(() => server.loadAccount(publicKey))
github michielmulders / stellar-js-sdk / src / app.js View on Github external
import rp from 'request-promise'
import Stellar from 'stellar-sdk'

/* Initialize app and configure bodyParser */
const port = process.env.PORT || 4000
const app = express()

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))

/* Global Vars */
const server = new Stellar.Server('https://horizon-testnet.stellar.org')
Stellar.Network.useTestNetwork()

let pairA = Stellar.Keypair.random()
let pairB = Stellar.Keypair.random()
let accountA, accountB = null

/* Stellar Interactions */
const createAccount = async (req, res) => {  
  // Create Account and request balance on testnet
  await rp.get({
    uri: 'https://horizon-testnet.stellar.org/friendbot',
    qs: { addr: pairA.publicKey() },
    json: true
  })

  accountA = await server.loadAccount(pairA.publicKey()) // Load newly created account

  // Print balances at account.balances[0].balance
  console.log('\nBalances for account: ' + pairA.publicKey())
  accountA.balances.forEach((balance) => {
github mikedeshazer / StellarXMarketMaker / lib / stellarSDKWrapper.js View on Github external
.then(async (account) => {
                let transaction = new StellarSdk.TransactionBuilder(account)
                    // Add a payment operation to the transaction
                    .addOperation(StellarSdk.Operation.createAccount({
                        destination: newPublicKey,
                        startingBalance: startingBalance, //At least 1 XLM to active new account
                    }))
                    // Uncomment to add a memo (https://www.stellar.org/developers/learn/concepts/transactions.html)
                    .addMemo(StellarSdk.Memo.text('Create a new account!'))
                    .build();

                // Sign this transaction with the secret key
                transaction.sign(srcKeyPair);

                // Let's see the XDR (encoded in base64) of the transaction we just built
                console.log(transaction.toEnvelope().toXDR('base64'));

                // Submit the transaction to the Horizon server. The Horizon server will then
                // submit the transaction into the network for us.
                return await server.submitTransaction(transaction)
github michielmulders / stellar-js-sdk / src / app.js View on Github external
const makePayment = async (req, res) => {
  const transaction = new Stellar.TransactionBuilder(accountA)
    .addOperation(Stellar.Operation.payment({
      destination: pairB.publicKey(),
      asset: Stellar.Asset.native(),
      amount: '30.0000001'
    }))
    .addOperation(Stellar.Operation.payment({
      destination: pairB.publicKey(),
      asset: Stellar.Asset.native(),
      amount: '2.0005682'
    }))
    .build()

  transaction.sign(pairA)

  // Let's see the XDR (encoded in base64) of the transaction we just built
  console.log("\nXDR format of transaction: ", transaction.toEnvelope().toXDR('base64'))

  try {
    const transactionResult = await server.submitTransaction(transaction)

    console.log('\n\nSuccess! View the transaction at: ')
    console.log(transactionResult._links.transaction.href)
github DnD-industries / stellar_tipping_bot / src / stellar / index.js View on Github external
.then(async function(sourceAccount) {
            // Start building the transaction.
            console.log("Source account sequence:", sourceAccount.sequenceNumber());
            while (sourceAccount.sequenceNumber() <= lastSequenceNumber) {
              console.log("Sequence number " + sourceAccount.account + " l.t.e. to last sequence of " + lastSequenceNumber);
              sourceAccount.incrementSequenceNumber();
              console.log("New source account sequence:", sourceAccount.sequenceNumber());
            }
            lastSequenceNumber = sourceAccount.sequenceNumber();
            var transaction = new StellarSdk.TransactionBuilder(sourceAccount)
              .addOperation(StellarSdk.Operation.payment({
                destination: to,
                // Because Stellar allows transaction in many currencies, you must
                // specify the asset type. The special "native" asset represents Lumens.
                asset: StellarSdk.Asset.native(),
                amount: amount
              }))
              // A memo allows you to add your own metadata to a transaction. It's
              // optional and does not affect how Stellar treats the transaction.
              // We substring here to limit memo strings to the allowed 28-byte maximum.
              .addMemo(StellarSdk.Memo.text(memo.length ? memo.substring(0,27) : "XLM Tipping Bot"))
              .build();
            // Sign the transaction to prove you are actually the person sending it.
            transaction.sign(keyPair);

            resolve(transaction);
github irisli / bookmaker / simplePayment.js View on Github external
module.exports = async function simplePayment(Server, account, keypair, opts) {
  const operationOpts = {
    destination: opts.destination,
    asset: opts.asset,
    amount: opts.amount,
  };

  const transaction = new StellarSdk.TransactionBuilder(account)
    .addOperation(StellarSdk.Operation.payment(operationOpts))
    // .addMemo(StellarSdk.Memo.text(`bookmaker ${version}`))
    .build();
  transaction.sign(keypair);

  const transactionResult = await Server.submitTransaction(transaction);
  // console.log('\n');
  // console.log(operationOpts);
  // console.log('View the transaction at: https://www.stellar.org/laboratory/#xdr-viewer?type=TransactionEnvelope&network=public&input=' + encodeURIComponent(transactionResult.envelope_xdr));
  // console.log('\n');
};
github DnD-industries / stellar_tipping_bot / src / adapters / abstract.js View on Github external
withdrawalAmount = new Big(amountRequested);
    } catch (e) {
      console.log(`Bad data fed to new Big() in Adapter::receiveWithdrawalRequest()\n${JSON.stringify(e)}`);
      console.log(`Withdrawal request amount is ${amountRequested}`);
      this.getLogger().CommandEvents.onWithdrawalInvalidAmountProvided(withdrawalRequest)
      return this.onWithdrawalInvalidAmountProvided(withdrawalRequest);
    }
    const fixedAmount = withdrawalAmount.toFixed(7);

    if(typeof address === 'undefined' || address === null) {
      this.getLogger().CommandEvents.onWithdrawalNoAddressProvided(withdrawalRequest)
        return this.onWithdrawalNoAddressProvided(withdrawalRequest);
    }


    if (!StellarSdk.StrKey.isValidEd25519PublicKey(address)) {
      this.getLogger().CommandEvents.onWithdrawalBadlyFormedAddress(withdrawalRequest, address)
      return this.onWithdrawalInvalidAddress(withdrawalRequest);
    }

    // Fetch the account
    const target = await withdrawalRequest.getSourceAccount();
    // TODO: Rather than having this fetch occur here, I think it might make more sense to move this to the  Command constructor
    if (!target.canPay(withdrawalAmount)) {
      this.getLogger().CommandEvents.onWithdrawalInsufficientBalance(withdrawalRequest, target.balance)
      return this.onWithdrawalFailedWithInsufficientBalance(withdrawalRequest, target.balance);
    }

    // Withdraw
    try {
      // txHash is the hash from the stellar blockchain, not our internal hash
      const txHash = await target.withdraw(this.config.stellar, address, withdrawalAmount, hash);
github satoshipay / solar / src / components / Subscribers.tsx View on Github external
/**
 * This file contains reactive components that subscribe to data (like an account balance) and
 * re-render their contents whenever the data changes.
 *
 * These components do not render any UI by themselves. Wrap your representational components in
 * them to obtain some data and receive live updates.
 */

import React from "react"
import { Server, Transaction } from "stellar-sdk"
import { observer } from "mobx-react"
import { subscribeToAccount, subscribeToRecentTxs, AccountObservable } from "../lib/subscriptions"

// TODO: Should probably be stored in context
const horizonLivenet = new Server("https://stellar-horizon.satoshipay.io/")
const horizonTestnet = new Server("https://stellar-horizon-testnet.satoshipay.io/")

type HorizonRenderProp = (horizon: Server) => React.ReactElement<any>

/**
 * @example
 * <Horizon testnet={false}>
 *   {horizon => (
 *     <div>Currently used horizon server: {horizon.serverURL}</div>
 *   )}
 * </Horizon>
 */
export const Horizon = (props: { children: HorizonRenderProp; testnet: boolean }) => {
  const horizon = props.testnet ? horizonTestnet : horizonLivenet
  return props.children(horizon)
}