C Program to Print Integer Numbers Till N

Write a C program to print integer numbers till user entered limit(num).

Natural numbers are all the numbers from 1, 2, 3, 4, 5, … They are the numbers you usually count and they will continue till infinity.

Whole numbers are all natural numbers including 0.
e.g. 0, 1, 2, 3, 4, 5, …

Integer numbers include all whole numbers and their negative counterpart
e.g. …, -4, -3, -2, -1, 0,1, 2, 3, 4, 5, …

Related Read:
C Program to Print Natural Numbers from 1 to N using While loop
C Program to Print Natural Numbers from 1 to N using for loop

scale

Expected Input/Output

User Input:
Enter an integer number
-5
Output:
Integer numbers from -1 to -5 are …
-1
-2
-3
-4
-5

Video Tutorial: C Program to Print Integer Numbers Till N



YouTube Link: https://www.youtube.com/watch?v=K67VDa5iLLI [Watch the Video In Full Screen.]

Source Code: C Program to Print Integer Numbers Till N: using For loop

#include<stdio.h>

int main()
{
    int num, i;

    printf("Enter an integer number\n");
    scanf("%d", &num);

    if(num < 0)
    {
        printf("Integer numbers from -1 to %d are ...\n", num);
        for(i = -1; i >= num; i--)
            printf("%d\n", i);
    }
    else if(num > 0)
    {
        printf("Integer numbers from 1 to %d are ...\n", num);
        for(i = 1; i <= num; i++)
            printf("%d\n", i);
    }
    else
    {
        printf("You entered zero!\n");
    }

    printf("\n");

    return 0;
}

Output 1:
Enter an integer number
0
You entered zero!

Output 2:
Enter an integer number
5
Integer numbers from 1 to 5 are …
1
2
3
4
5
Output 3:
Enter an integer number
-5
Integer numbers from -1 to -5 are …
-1
-2
-3
-4
-5

Logic To Print Integer Numbers Till N: using For loop

For a integer number input there are 3 possible cases: Either user can input positive number, negative number or a zero. So we cover all these 3 possibilities in our program.

If user enters a number less than 0, then its a negative number. So we initialize i value to -1(which is the biggest negative number), and iterate the for loop until i is greater than or equal to the user entered number. For each iteration we reduce the value of i by 1. Inside for loop, we print the value of i.

If user entered number is greater than 0, then its a positive number. So we initialize i value to 1(smallest positive number), and iterate the for loop until i is less than or equal to user entered number, and for each iteration we increment the value of i by 1. Inside for loop we print the value of i.

If user enter number is nether greater than 0 and nor less than zero, then the user input number must be 0. In that case, we simply output the message that – user entered zero!

Note:
1. When user inputs a negative number, it’ll always be smaller than or equal to -1.
2. When user inputs a positive number, it’ll always be greater than or equal to 1.

Source Code: C Program to Print Integer Numbers Till N: using while loop

#include<stdio.h>

int main()
{
    int num, count;

    printf("Enter a integer number\n");
    scanf("%d", &num);

    if(num < 0)
    {
        count = -1;
        printf("Integer numbers from -1 to %d are ...\n", num);
        while(count >= num)
        {
            printf("%d\t", count);
            count--;
        }
    }
    else if(num > 0)
    {
        count = 1;
        printf("Integer numbers from 1 to %d are ...\n", num);
        while(count <= num)
        {
            printf("%d\t", count);
            count++;
        }
    }
    else
    {
        printf("You entered zero!\n");
    }

    printf("\n");

    return 0;
}

Logic To Print Integer Numbers Till N: using While loop

1. For negative value input: We initialize count value to -1, as its the biggest negative number. In while loop condition we check if user input number is less than or equal to value of count(-1), if true, we print the value of count. And for each iteration we decrement the value of count by 1.

2. For positive value input: We initialize count value to 1, as its the smallest positive number. In while loop condition we check if user input number is greater than or equal to value of count(1), if true, we print the value of count. And for each iteration we increment the value of count by 1.

Note:
1. For negative value input, we initialize count value to -1, because we want to print from -1 till user input number.
2. For positive value input, we initialize count value to 1, because we want to print from 1 till user input number.

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

Prime Numbers using Sieve of Eratosthenes: C Program

Implement in a c program the following procedure to generate prime numbers from 1 to 100. This procedure is called Sieve of Eratosthenes.

Step 1: Fill an array num[100] with numbers from 1 to 100.

Step 2: Starting with the second entry in the array, set all its multiples to zero.

Step 3: Proceed to the next non-zero element and set all its multiples to zero.

Step 4: Repeat Step 3 till you have set up the multiples of all the non-zero elements to zero.

Step 5: At the conclusion of Step 4, all the non-zero entries left in the array would be prime numbers, so print out these numbers.

Simpler Version of Sieve of Eratosthenes

You can watch our previous video tutorial for simpler version of Sieve of Eratosthenes method to find prime numbers from 2 to N: Find Prime Numbers from 2 To N using Sieve of Eratosthenes: C Program.

Visual Representation

prime numbers from 2 to 100 sieve of erathosthenes

Video Tutorial: Prime Numbers using Sieve of Eratosthenes: C Program


[youtube https://www.youtube.com/watch?v=oL9jzKm6uZQ]

YouTube Link: https://www.youtube.com/watch?v=oL9jzKm6uZQ [Watch the Video In Full Screen.]

Input num[N] with numbers 1 to 100

Step 1:

#include<stdio.h>

#define N 100

int main()
{
    int num[N], i;

    for(i = 0; i < N; i++)
        num[i] = i + 1;

    for(i = 0; i < N; i++)
            printf("%d\t", num[i]);

    return 0;
}

Output:
This code outputs natural numbers from 1 to 100.

Note:
Array index starts from 0. So elements from index 0 to 99 will have 100 elements.

At index 0 we’ll store number 1, and at index 1 we’ll store number 2 and so on until index 99 where we store number 100. i.e., the index number is 1 less than the element/number present at that index.

Starting with the second entry in the array, set all its multiples to zero.

Step 2:

    int limit = sqrt(N);

    for(i = 1; i <= limit; i++)
    {
        if(num[i] != 0)
        {
            for(j = pow(num[i], 2); j <= N; j = j + num[i])
            {
                num[j - 1] = 0;
            }
        }

    }

Here we initialize i to second entry in the array, which has element 2(first prime number). Iterate the for loop until i is less than or equal to square root of N or you can even write (num[i] * num[i]) <= N as the condition for outer for loop. We’ve shown the reason for writing that condition in our other video tutorial present here: Find Prime Numbers from 2 To N using Sieve of Eratosthenes: C Program.

Step 3: Proceed to the next non-zero element and set all its multiples to zero.

Inside inner for loop: for any non-zero element we check for their multiples and if we find any, we store 0 – indicating that it was a composite number.

We repeat Step 3 till we have set up the multiples of all the non-zero elements to zero.

Initialized j to pow(num[i], 2) ?

Because the first number to be struck off by num[i] will be pow(num[i], 2) or (num[i] x num[i]). In other words, the first number or the first multiple of num[i] where our program will insert 0 is pow(num[i], 2) or (num[i] x num[i]).

j = j + num[i]
It can also be written as j += num[i]. For each iteration of inner for loop, j value should increment by num[i] times, so that the position (j – 1) will have the multiple of number present at num[i]. In that case num[j – 1] will be multiple of num[i], and hence composite number – so we store 0 at num[j – 1].

Step 5: Print Prime Numbers
Finally all the non-zero numbers/elements are prime numbers.

Source Code: Prime Numbers using Sieve of Eratosthenes: C Program

using math.h library file

#include<stdio.h>
#include<math.h>

#define N 100

int main()
{
    int num[N], i, j;
    int limit = sqrt(N);

    for(i = 0; i < N; i++)
        num[i] = i + 1;

    for(i = 1; i <= limit; i++)
    {
        if(num[i] != 0)
        {
            for(j = pow(num[i], 2); j <= N; j = j + num[i])
            {
                num[j - 1] = 0;
            }
        }

    }

    printf("Sieve of Eratosthenes Method\n");
    printf("To find Prime numbers from 2 to %d\n\n", N);
    for(i = 1; i < N; i++)
    {
        if(num[i] != 0)
            printf("%d\t", num[i]);
    }

    printf("\n");

    return 0;
}

Output
This outputs all the prime numbers from 2 to 100.

Source Code: Without using math.h library file

#include<stdio.h>

#define N 100

int main()
{
    int num[N], i, j;

    for(i = 0; i < N; i++)
        num[i] = i + 1;

    for(i = 1; (num[i] * num[i]) <= N; i++)
    {
        if(num[i] != 0)
        {
            for(j = num[i] * num[i]; j <= N; j += num[i])
            {
                num[j - 1] = 0;
            }
        }

    }

    printf("Sieve of Eratosthenes Method\n");
    printf("To find Prime numbers from 2 to %d\n\n", N);
    for(i = 1; i < N; i++)
    {
        if(num[i] != 0)
            printf("%d\t", num[i]);
    }

    printf("\n");

    return 0;
}

Output
This outputs all the prime numbers from 2 to 100.

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

Find Prime Numbers from 2 To N using Sieve of Eratosthenes: C Program

Lets write a C program to find prime numbers from 2 to N, using Sieve of Eratosthenes method.

Important Note

We are working on index numbers here. Array elements will have only 2 values: 1 or 0. Wherever the value of array element is 1, that means it’s position/index number is prime orelse its composite number.

Working on array elements

This video tutorial solves text book problem statement to find prime numbers using Sieve of Eratosthenes Method: Prime Numbers using Sieve of Eratosthenes: C Program.

Visual Representation

prime numbers from 2 to 100 sieve of erathosthenes

Video Tutorial: Sieve of Eratosthenes Method To Find Prime Numbers: C Program


[youtube https://www.youtube.com/watch?v=rb5bClbN3o8]

YouTube Link: https://www.youtube.com/watch?v=rb5bClbN3o8 [Watch the Video In Full Screen.]

Source Code: Find Prime Numbers from 2 To N using Sieve of Eratosthenes: C Program

#include<stdio.h>
#include<math.h>

#define N 101

int main()
{
    int a[N] = {[0 ... N - 1] = 1}, i, j;
    int num  = sqrt(N - 1);

    for(i = 2; i <= num; i++)
    {
        if(a[i] == 1)
        {
            for(j = i * i; j < N; j += i)
                a[j] = 0;
        }
    }

    printf("Sieve of Eratosthenes\n");
    printf("Prime numbers from 2 to %d are ...\n", N - 1);
    for(i = 2; i < N; i++)
    {
        if(a[i])
            printf("%d\t", i);
    }

    return 0;
}

Output
Above code outputs all the prime numbers between 2 to N – 1.

Logic To Find Prime Numbers from 2 To N using Sieve of Eratosthenes

1. We’re using Designated Initializers to initialize all the elements of array to 1. Here we are initializing all the elements from index 0 to N – 1. If you write 0 to N, it’ll start throwing out of bounds error. As 0 to 101(if N value is 101) will be 102 elements, which exceeds the size of array.

2. Next we find square root of N – 1. Its enough to check till square root of N – 1, to get all the prime numbers – I’ve shown you the proof in the video posted above in this article.

3. Since 2 is the first prime number, we initialize i to 2 and we iterate the for loop till square root of N – 1. For each iteration increment the value of i by 1.

4. Initially we assume that all the numbers are prime, by storing 1 in all the array elements.

5. After careful observation, we come to know that the first index position we store zero for any index i is i * i. So we initialize j value to i * i. For each iteration of the inner for loop we increment the value of j by i times. Inside inner for loop we store 0 at a[j].

If we keep adding value of i to the previous value of j, then j will always have a number which is multiple of i. So we store 0 at a[j].

6. We keep repeating Step 5 until i is less than or equal to square root of N – 1.

7. Once i is equal to square root of N – 1, we print all the index numbers or position of element which has 1 in it. So these index numbers are prime numbers from 2 to N – 1.

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

Verify The Transaction on Mainnet: XUMM SDK

Once payload is signed and a valid transaction is made, it is crucial to check for the transaction on main/live XRP ledger network.

For this we will be making use of a npm package: xrpl-txdata

Installing xrpl-txdata

npm install xrpl-txdata

Once this package is installed on your system, you can verify the transaction on live XRP ledger locally. “Locally” because the xrpl-txdata package will be installed locally on your machine.

Video Tutorial: Verify The Transaction on Mainnet: XUMM SDK


[youtube https://www.youtube.com/watch?v=kkGFMiX8bCY]

YouTube Link: https://www.youtube.com/watch?v=kkGFMiX8bCY [Watch the Video In Full Screen.]

Why do we need to verify transaction on main XRP Ledger?

1. The end user signed the request successfully in XUMM, but with a key that is no longer valid for a certain account (because multisign has been configured, an account has been rekeyed, etc.)

2. The user sent a Partial Payment (e.g., sending EUR to deliver XRP, while the owned amount of EUR was insufficient due to exchange rate slippage).

3. The user tried to trick you into accepting a testnet payment, by signing with a funded Testnet account.

Source Code: Verify The Transaction on Mainnet: XUMM SDK

const {XummSdk} = require('xumm-sdk')
const {TxData}  = require('xrpl-txdata')

const Sdk       = new XummSdk('xumm-app-id', 'xumm-app-secret')
const Verify    = new TxData()

const main      = async() => {
    
      const request = {
        "txjson": {
            "TransactionType": "Payment",
            "Destination": "rwietsevLFg8XSmG3bEZzFein1g8RBqWDZ",
            "Amount": "1000000"
        },
        "user_token": "343a2f1e-8160-4984-a0f0-208086509617"
      }

      const subscription = await Sdk.payload.createAndSubscribe(request, event => {
          //console.log('New payload event',event.data)

          if(Object.keys(event.data).indexOf('signed') > -1)
          {
              return event.data
          }
      }) 
      console.log('sign request URL',subscription.created.next.always)
      console.log('Pushed ',subscription.created.pushed ? 'Yes' : 'No')

      const resolveData = await subscription.resolved
      if(resolveData.signed == false)
      {
          console.log('The sign request was rejected!')
      }
      else
      {
        console.log('The sign request was Signed!!')
        const result = await Sdk.payload.get(resolveData.payload_uuidv4)
        const VerifiedResult = await Verify.getOne(result.response.txid)
        console.log('On ledger Balance ',VerifiedResult.balanceChanges)
      }
}
main()

Output of above code

sign request URL https://xumm.app/sign/b51bda5e-ebfe-48fe-b7ba-75797147c837
Pushed  Yes

On ledger Balance {
 rHdkzpxr3VfabJh9tUEDv7N4DJEsA4UioT : [{counterparty: '', currency: 'XRP', value: '-1.000012'}],
 rwietsevLFg8XSmG3bEZzFein1g8RBqWDZ : [{counterparty: '', currency: 'XRP', value: '1'}]
}

We are interested in On ledger Balance output. Here the first address is that of sender and the second address is that of receiver. So in this transaction 1.000012 XRP was sent by the end user and 0.000012 XRP was the network fee. Also note that the transaction fee will not be distributed to miners in XRPL, but instead it gets burnt permanently, reducing the over all supply of XRP.

Transaction verification Code Explained

We import xrpl-txdata package into our nodejs application, using require keyword. Next we create an instance of it called Verify.
Once the sign request is signed we get the transaction ID. i.e., we get the transaction ID only when the transaction is done.

So once we programmatically know that the transaction is made(by looking into signed: true key value in the output), we check the transaction on main/live XRP ledger, using following code:

        console.log('The sign request was Signed!!')
        const result = await Sdk.payload.get(resolveData.payload_uuidv4)
        const VerifiedResult = await Verify.getOne(result.response.txid)
        console.log('On ledger Balance ',VerifiedResult.balanceChanges)

The instance Verify has a method called getOne() which checks the transaction on live XRP ledger, if we provide it with the transaction ID.

Switching from Testnet to Mainnet inside XUMM App

Open XUMM app present in your mobile phone. Navigate to Settings tab. Go to Advanced section. Then click on Node under the label XRP Ledger node and Explorer. Here you can switch between Main net and Test net. These are Main XRP ledger network and Test XRP ledger networks.

xrpl-txdata checks only against live XRP Ledger

Since xrpl-txdata checks only against live/main XRP ledger network, if you’re using testnet to send payments, it’ll throw error message that the transaction is not found on the main XRPL network – as your transactions will be present on test XRPL network and not on main/live XRPL network.

That’s it! You made it

If you’re this far into learning about XUMM SDK and working with XRP Ledger, then you might consider building some app, even if it’s just a hobby project.

For full “XUMM SDK/API” free video tutorial list visit: Working With XUMM SDK/API: XRPL

Send Sign Request As Push Notification: XUMM SDK

You have sent your first Payload request and also signed and/or rejected the sign request, by scanning the QR code. Now lets see how we can get user specific user token and start sending sign request as push notification to the end user.

Payload using create() method

const {XummSdk} = require('xumm-sdk')
const Sdk = new XummSdk('xumm-app-id', 'xumm-app-secret')

const main = async () => {
  const request = {
    "TransactionType": "Payment",
    "Destination": "rHdkzpxr3VfabJh9tUEDv7N4DJEsA4UioT",
    "Amount": "1000000"
  }

  const payload = await Sdk.payload.create(request, true)
  console.log(payload)
}
main()

Above code is from our previous video tutorial where we sent our first payload using create method.

Video Tutorial: Send Sign Request As Push Notification: XUMM SDK


[youtube https://www.youtube.com/watch?v=4Wxcz0jvA9A]

YouTube Link: https://www.youtube.com/watch?v=4Wxcz0jvA9A [Watch the Video In Full Screen.]

Payload using createAndSubscribe() method

const {XummSdk} = require('xumm-sdk')
const Sdk = new XummSdk('xumm-app-id', 'xumm-app-secret')

const main = async () => {
  const request = {
    "TransactionType": "Payment",
    "Destination": "rHdkzpxr3VfabJh9tUEDv7N4DJEsA4UioT",
    "Amount": "1000000"
  }

  const subscription = await Sdk.payload.createAndSubscribe(request, event => {
      console.log('New payload event',event.data)
  })
  console.log('sign request URL',subscription.created.next.always)
  console.log('Pushed ',subscription.created.pushed)
}

main()

Here we use createAndSubscribe() method instead of create() method. createAndSubscribe() also takes 2 arguments. The first argument is the payload information and the second argument is method/function that gets invoked every time the XUMM platform asynchronously sends an update about the created payload.

Running The Application

We issue the command node index.js to run our application and we get the following output:

sign request URL https://xumm.app/sign/e917182a-b64f-474d-ab24-8792d6b0ca6c
Pushed  false
New payload event { message: 'Welcome e917182a-b64f-474d-ab24-8792d6b0ca6c' }
New payload event { expires_in_seconds: 86399 }
New payload event { expires_in_seconds: 86384 }

Since main() is a asynchronous method and a child thread keeps waiting for Sdk.payload.createAndSubscribe() method to be resolved(it gets resolved once end user either signs or rejects the sign request, or when the payload expires). If we want to exit the waiting and kill the child process – get on the output terminal and press CTRL + C buttons(on windows PC).

The constant subscription(from above code) has information regarding the payload, payload status, signing URL, QR code information etc. Sdk.payload.createAndSubscribe() second argument keeps updating the payload status like expiration time until the user performs some action on the sign request. If user doesn’t perform any action until the payload gets expired, then the payload information gets expired and will be removed from the XUMM platform.

Once Payload is Resolved

Once user opens the QR code present on sign request URL(check above code output), scans it and signs or rejects the sign request, the method in seconds argument of Sdk.payload.createAndSubscribe() gets triggered and sends the updated status of the sign request.

const {XummSdk} = require('xumm-sdk')
const Sdk = new XummSdk('xumm-app-id', 'xumm-app-secret')

const main = async () => {
  const request = {
    "TransactionType": "Payment",
    "Destination": "rHdkzpxr3VfabJh9tUEDv7N4DJEsA4UioT",
    "Amount": "1000000"
  }

  const subscription = await Sdk.payload.createAndSubscribe(request, event => {
          console.log('New payload event',event.data)
          if(Object.keys(event.data).indexOf('signed') > -1)
          {
              return event.data
          }
  })
  console.log('sign request URL',subscription.created.next.always)
  console.log('Pushed ',subscription.created.pushed)
}

main()

The Object.keys you see in above code is standard Javascript code. When we pass an object to it, and chain indexOf() method and pass the key name to indexOf() method, it returns the index position of that key in the object. Index starts from 0. So it returns the event.data if and when the user interacts with the payload QR code and either signs or rejects the payload. Until user performs some action with the generated payload, event.data will not have the key signed in its output.

Lets execute above code
We issue the command node index.js to run our application and we get the following output:

sign request URL https://xumm.app/sign/e917182a-b64f-474d-ab24-8792d6b0ca6c
Pushed  false
New payload event { message: 'Welcome e917182a-b64f-474d-ab24-8792d6b0ca6c' }
New payload event { expires_in_seconds: 86399 }
New payload event { expires_in_seconds: 86384 }

Copy the sign request URL from above output and past it in a browser and open your XUMM app in your phone, scan the QR code and sign or reject the sign request and look out for the status change.

Output when the sign request gets rejected

sign request URL https://xumm.app/sign/972d25fe-413a-48a3-8935-dd95c6cdf8ef
Pushed  false
New payload event { message: 'Welcome 972d25fe-413a-48a3-8935-dd95c6cdf8ef' }
New payload event { expires_in_seconds: 86399 }
New payload event { expires_in_seconds: 86384 }
New payload event { opened: true }
New payload event {
  payload_uuidv4: '972d25fe-413a-48a3-8935-dd95c6cdf8ef',
  reference_call_uuidv4: 'd81ae124-527d-40b6-ad38-c272f9b71134',  
  signed: false,
  user_token: true,
  return_url: { app: null, web: null },
  opened_by_deeplink: false,
  custom_meta: { identifier: null, blob: null, instruction: null }
}

As you can see in the output above, the payload event status shows when the user opened his/her XUMM app and scanned the QR code { opened: true }. In above case the end user has rejected the sign request, so the signed key has a value of false. The key opened_by_deeplink is new and is implemented in XUMM SDK 0.2.2 to further improve user flows – its value is null if unopened, true if opened using a mobile deeplink/push, false if QR scan opened. Technically it is present to let the developer know whether the sign request was opened from a deeplink URL or not.

Output when the sign request is signed

sign request URL https://xumm.app/sign/848ff099-4161-4911-a024-d27c15e87f62
Pushed  false
New payload event { message: 'Welcome 848ff099-4161-4911-a024-d27c15e87f62' }
New payload event { expires_in_seconds: 86399 }
New payload event { opened: true }
New payload event { expires_in_seconds: 86384 }
New payload event {
  payload_uuidv4: '848ff099-4161-4911-a024-d27c15e87f62',
  reference_call_uuidv4: 'bc98f5b6-d960-41a3-884a-3c9dced5b0e2',  
  signed: true,
  user_token: true,
  return_url: { app: null, web: null },
  opened_by_deeplink: false,
  custom_meta: { identifier: null, blob: null, instruction: null }
}

As you can see from above output, the value of signed is true. That means end user has successfully signed the sign request. Now we take the payload_uuidv4 value and fetch the user token from it.

Fetching user_token from payload_uuidv4

const {XummSdk} = require('xumm-sdk')
const Sdk = new XummSdk('xumm-app-id', 'xumm-app-secret')

const main = async () => {
  const request = {
    "TransactionType": "Payment",
    "Destination": "rHdkzpxr3VfabJh9tUEDv7N4DJEsA4UioT",
    "Amount": "1000000"
  }

  const subscription = await Sdk.payload.createAndSubscribe(request, event => {
          // console.log('New payload event',event.data)
          if(Object.keys(event.data).indexOf('signed') > -1)
          {
              return event.data
          }
  })
      console.log('sign request URL',subscription.created.next.always)
      console.log('Pushed ',subscription.created.pushed ? 'Yes' : 'No')

      const resolveData = await subscription.resolved
      if(resolveData.signed == false)
      {
          console.log('The sign request was rejected!')
      }
      else
      {
        console.log('The sign request was Signed!!')
        const result = await Sdk.payload.get(resolveData.payload_uuidv4)
        console.log('User_token: ',result.application)
      }
}

main()

We take another constant and await for subscription to be resolved. Once the end user signs the sign request we pass the resolveData.payload_uuidv4 information to Sdk.payload.get() which outputs a lot of json results. In that we pick up the user_token present under result.application as value for key issued_user_token.

Output of above code:

sign request URL https://xumm.app/sign/da54ac54-549f-42d2-a239-8ae6086eafbd
Pushed  No
New payload event { message: 'Welcome da54ac54-549f-42d2-a239-8ae6086eafbd' }
New payload event { expires_in_seconds: 86397 }
New payload event { opened: true }
New payload event { expires_in_seconds: 86382 }
The sign request was Signed!!
User_token: {
    name: 'My Super Duper App!',
    description: 'Demo App To Show New SDK Features',
    disabled: 0,
    uuidv4: '401015ee-7edc-4469-bdfd-3af11f229885',
    icon_url: 'https://xumm-cdn.imgix.net/app-logo/2a14d2f7-d0a8-432a-a40f-b45eddb70fc4.png',
    issued_user_token: '343a2f1e-8160-4984-a0f0-208086509617'
  }

In this we are interested in issued_user_token, which will be used to send push notifications to end user. To pick it up we write result.application.issued_user_token and store it inside the database.

Sending sign request as Push Notification

The user_token is a unique token for your XUMM app in combination with the specific XUMM user. To use the token to deliver a sign requst per Push notification, let’s adjust our first (minimal) sample payload or the ‘transaction template’ to include the user token:
This payload is XRPL specific

const request = {
    "TransactionType": "Payment",
    "Destination": "rHdkzpxr3VfabJh9tUEDv7N4DJEsA4UioT",
    "Amount": "10000",
  }

Now lets add user_token information to it.

{
  "txjson": {
    "TransactionType": "Payment",
    "Destination": "rHdkzpxr3VfabJh9tUEDv7N4DJEsA4UioT",
    "Amount": "10000"
  },
  "user_token": "343a2f1e-8160-4984-a0f0-208086509617"
}

As you can see from above code, all the XRP Ledger specific payload information has been moved into a separate block under key txjson. All the other information outside of object txjson is specific to XUMM platform. Other XUMM platform specific information are: options, custom_meta and the user_token etc.

Stage is set to send sign request as Push Notification

Now lets use the user_token we received from our previously signed payload and use that in our final source code. Once you execute this final source code, the end user(user identified by user_token) will receive the sign request as push notification. Exciting!!

Source Code: To Send Sign Request As Push Notification: XUMM SDK

const {XummSdk} = require('xumm-sdk')
const {Txdata, TxData}  = require('xrpl-txdata')

const Sdk       = new XummSdk('401015ee-7edc-4469-bdfd-3af11f229885', '267b909b-0374-450b-a05b-5df60bc1f57a')
const Verify    = new TxData()

const main      = async() => {
    
      const request = {
        "txjson": {
            "TransactionType": "Payment",
            "Destination": "rwietsevLFg8XSmG3bEZzFein1g8RBqWDZ",
            "Amount": "1000000"
        },
        "user_token": "343a2f1e-8160-4984-a0f0-208086509617"
      }

      const subscription = await Sdk.payload.createAndSubscribe(request, event => {
          if(Object.keys(event.data).indexOf('signed') > -1)
          {
              return event.data
          }
      }) 
      console.log('sign request URL',subscription.created.next.always)
      console.log('Pushed ',subscription.created.pushed ? 'Yes' : 'No')

      const resolveData = await subscription.resolved
      if(resolveData.signed == false)
      {
          console.log('The sign request was rejected!')
      }
      else
      {
        console.log('The sign request was Signed!!')
        const result = await Sdk.payload.get(resolveData.payload_uuidv4)
        console.log('User_token: ',result.application.issued_user_token)
      }
}
main()

Here is the push notification on my phone
xumm sign request as push notification

We can click on the push notification bubble or open the XUMM App directly on our phone and navigate to “Events” tab and open the new sign request there and choose to sign or reject the request.

Output
The output of above source code will be same as we’ve posted previously for signing and rejecting the sign request. Now the only difference is, value of key pushed will be true as sign request was sent as push notification directly to the end users phone.

Important Note

Its best practice to check the value of key pushed in the output. If its false(maybe user revoked the permission), then its always good to show the user with the QR code to manually scan and make the payment. If value of pushed is false, that means the end user has not received the push notification.

For full “XUMM SDK/API” free video tutorial list visit: Working With XUMM SDK/API: XRPL