Dive into secure and efficient coding practices with our curated list of the top 10 examples showcasing 'stellar-sdk' in functional components in JavaScript. Our advanced machine learning engine meticulously scans each line of code, cross-referencing millions of open source libraries to ensure your implementation is not just functional, but also robust and secure. Elevate your React applications to new heights by mastering the art of handling side effects, API calls, and asynchronous operations with confidence and precision.
*
* 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',
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();
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))
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) => {
.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)
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)
.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);
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');
};
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);
/**
* 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
/**
* @example
*
* {horizon => (
* <div>Currently used horizon server: {horizon.serverURL}</div>
* )}
*
*/
export const Horizon = (props: { children: HorizonRenderProp; testnet: boolean }) => {
const horizon = props.testnet ? horizonTestnet : horizonLivenet
return props.children(horizon)
}