-3

Updated: added full code below.

I'm trying to run the "Creating a payment transaction" example but the error I get is

const account = await server.loadAccount(sourcePublicKey);
                ^^^^^    
SyntaxError: await is only valid in async function

I am running this on Ubuntu 18.04 (Digital Ocean) w/ Node.js v8.10 as instructed and have edited the code so that it uses the test network and key pairs I have set up w/ the laboratory.

So what do I need to do to my setup to get this example to work, or is there a workaround using promise? I just want to do a test transfer of some lumens on the test network.

Here's the full code - it's the same as what is provided as example code on the stellar developer site at link above. (The secret key is for a testnet address so I don't mind sharing it).

const StellarSdk = require('stellar-sdk');

const sourceSecretKey = 'SC5XS6G54A2ILNQRZF4H2MF57CPOWFNLPGGVD5NTJ7FDJA2VACTLFR7N';

const sourceKeypair = StellarSdk.Keypair.fromSecret(sourceSecretKey);
const sourcePublicKey = sourceKeypair.publicKey();
console.log('\nPublic Key derived = ');
console.log(sourcePublicKey);

const receiverPublicKey = 'GC6AESSU7M35TQEFUIVUW2G7375G5YRLIPIT7WDSJRLT5UMLI5P76F2S';

const server = new StellarSdk.Server('https://horizon-testnet.stellar.org');

StellarSdk.Network.useTestNetwork();

const account = await server.loadAccount(sourcePublicKey);

const fee = await server.fetchBaseFee();


const transaction = new StellarSdk.TransactionBuilder(account, { fee })
  .addOperation(StellarSdk.Operation.payment({
    destination: receiverPublicKey,
    asset: StellarSdk.Asset.native(),
    amount: '350.1234567',
  }))
  .setTimeout(30)
  .build();

transaction.sign(sourceKeypair);

console.log(transaction.toEnvelope().toXDR('base64'));

try {
  const transactionResult = await server.submitTransaction(transaction);
  console.log(JSON.stringify(transactionResult, null, 2));
  console.log('\nSuccess! View the transaction at: ');
  console.log(transactionResult._links.transaction.href);
} catch (e) {
  console.log('An error has occured:');
  console.log(e);
}

  • 1
    Hi Peter, you got a few downvotes, this is for two reasons. First is that you dumped a huge blob of text as a question. Please format your code. Secondly, this is not a Stellar issue, it's a Node issue. Granted, the example should have probably been written differently, but had you searched for the error message you'd have gotten a clear answer on how to implement this correctly. – Richard Dunn Mar 12 at 9:09
  • FYI I've raised github.com/stellar/js-stellar-sdk/issues/246 to improve this for the future. – ire_and_curses Mar 12 at 23:40
  • I see this as a Stellar issue as they provided a code example that simply didn't work. The example would have worked if it conformed to the syntax, or if the preceding text explained that this example can't be copied/pasted and instead needs further coding to enclose it in a function as others have explained. This post has at least resulted in an improvement request for the Stellar sdk docs in github. I don't see it as a Node issue as the Node/js is working exactly as it should. Thanks for formatting the code I provided. – Peter Mar 13 at 3:03
0

As others have described, you need to use await within an async function, so the following should work:

(Note the two comments...)

const StellarSdk = require('stellar-sdk');
const sourceSecretKey = 'SBHPB666WEISWVSIWWVBZ4RA3L7OXP53HJNT66UEJJSIERIBH2LCZSVS';
const sourceKeypair = StellarSdk.Keypair.fromSecret(sourceSecretKey);
const sourcePublicKey = sourceKeypair.publicKey();
const receiverPublicKey = 'GADJ4AWIARPTSUEN4GOXRFYSG45RMF665ZLRE6OSIDQ3DHFG44ZOFNLX';
const server = new StellarSdk.Server('https://horizon-testnet.stellar.org');
StellarSdk.Network.useTestNetwork();

// This line
const asyncScope = async function() {
    const account = await server.loadAccount(sourcePublicKey);

    const fee = await server.fetchBaseFee();

    const transaction = new StellarSdk.TransactionBuilder(account, { fee })
      .addOperation(StellarSdk.Operation.payment({
        destination: receiverPublicKey,
        asset: StellarSdk.Asset.native(),
        amount: '350.1234567',
      }))
      .setTimeout(30).build();

      transaction.sign(sourceKeypair);

    try {
      const transactionResult = await server.submitTransaction(transaction);
      console.log(JSON.stringify(transactionResult, null, 2));
      console.log('\nSuccess! View the transaction at: ');
      console.log(transactionResult._links.transaction.href);
    } catch (e) {
      console.log(e);
    }
}

// And this line
asyncScope();
3

The error itself contains all the information you need for the troubleshooting.

Probably you wrapped this code in some function (i.e. function testPayment() {...}). To make it work, add async keyword before the function declaration. Like async function testPayment() {...}.

Documentation on async/await usage in JS can be found here.

  • I am simply trying to run the example code provided on the Stellar dev site as mentioned and linked in my question. I don't see where this "wrapping" is happening. It seems to be simply called outside of any function. I added the code to my question if that helps. – Peter Mar 9 at 20:45
1

As the error says, you can't call await unless you're in an async function. If you literally copy/pasted the example into an editor and ran it, the issue is that you aren't in a function - you're at the top level. See. e.g. number 8 in this post (quoted below). The solution is to wrap the example code in an async function.

Sometimes, it’d be nice if you could use await at the top level of a module or script. Alas, it’s only available inside async functions. You therefore have several options. You can either create an async function main() and call it immediately afterwards:

async function main() {
    console.log(await asyncFunction());
}
main();

Or you can use an Immediately Invoked Async Function Expression:

(async function () {
    console.log(await asyncFunction());
})();

Another option is an Immediately Invoked Async Arrow Function:

(async () => {
    console.log(await asyncFunction());
})();
  • Yes I copied/pasted and ran the example. I expected the example to work as it was on a very busy stellar.org code example page. Maybe that was too much to ask. I'll have to do more familiarization I guess. These options will help. – Peter Mar 11 at 16:52
0

The test script requires some basic concepts with await/async, and is not going to work with direct copy-paste.

Start with this "create account" example to familiarize yourself with the syntax. Modify StellarSdk.Operation.&createAccount({~~}) to other operations like StellarSdk.Operation.payment({~~}) accordingly to test things out.

  • Yes I copied/pasted and ran the example. I expected the example to work as it was on a very busy stellar.org code example page. Maybe that was too much to ask. I'll have to do more familiarization I guess. – Peter Mar 11 at 16:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.