Skip to content

Instantly share code, notes, and snippets.

@JesseAbram
Created April 12, 2019 15:30
Show Gist options
  • Save JesseAbram/d3701e3a957a5bc29b69a1b3e6a60417 to your computer and use it in GitHub Desktop.
Save JesseAbram/d3701e3a957a5bc29b69a1b3e6a60417 to your computer and use it in GitHub Desktop.
const StellarSdk = require('stellar-sdk');
const checkIfAccountExists = async (to, server) => {
try {
await server
.accounts()
.accountId(to)
.call();
return true;
} catch (err) {
return false;
}
};
const createTxnForExistingAccount = async (to, wallet, token, fee, server) => {
const sourceKeypair = await StellarSdk.Keypair.fromSecret(wallet.privateKey);
const sourcePublicKey = sourceKeypair.publicKey();
StellarSdk.Network.useTestNetwork();
const account = await server.loadAccount(sourcePublicKey);
const transaction = new StellarSdk.TransactionBuilder(account, { fee })
.addOperation(
StellarSdk.Operation.payment({
destination: to,
asset: StellarSdk.Asset.native(),
amount: token.maxSupplyAllowed
})
)
.setTimeout(30)
.build();
transaction.sign(sourceKeypair);
const txn = await server.submitTransaction(transaction);
return txn.hash;
};
const createAccount = async (to, wallet, token, fee, server) => {
const sourceKeypair = await StellarSdk.Keypair.fromSecret(wallet.privateKey);
StellarSdk.Network.useTestNetwork();
const { sequence } = await server
.accounts()
.accountId(sourceKeypair.publicKey())
.call();
const account = new StellarSdk.Account(sourceKeypair.publicKey(), sequence);
const transaction = new StellarSdk.TransactionBuilder(account, {
fee: StellarSdk.BASE_FEE
})
.addOperation(
StellarSdk.Operation.createAccount({
destination: to,
startingBalance: token.maxSupplyAllowed
})
)
.setTimeout(30)
.build();
transaction.sign(StellarSdk.Keypair.fromSecret(sourceKeypair.secret()));
const submitTxn = await server.submitTransaction(transaction);
return submitTxn.hash;
};
exports.createTransaction = async (to, wallet, token) => {
const server = new StellarSdk.Server(token.networkUrl);
const fee = await server.fetchBaseFee();
const account = await checkIfAccountExists(to, server);
if (account){
const hash = createTxnForExistingAccount(to, wallet, token, fee, server);
return hash;
} else {
const hash = createAccount(to, wallet, token, fee, server);
return hash;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment