<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Gary George on Medium]]></title>
        <description><![CDATA[Stories by Gary George on Medium]]></description>
        <link>https://medium.com/@garygeorge84?source=rss-4a42073343ff------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*2Jct9dFFhi08Vbae.</url>
            <title>Stories by Gary George on Medium</title>
            <link>https://medium.com/@garygeorge84?source=rss-4a42073343ff------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 04:15:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@garygeorge84/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Algorithms & Data Structures— A beginners guide  ]]></title>
            <link>https://garygeorge84.medium.com/algorithms-data-structures-a-beginners-guide-2ed17c17e879?source=rss-4a42073343ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ed17c17e879</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Gary George]]></dc:creator>
            <pubDate>Sat, 11 May 2024 23:14:30 GMT</pubDate>
            <atom:updated>2024-05-11T23:14:30.916Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6lQrfV6IfFJCUqoqcBBXzQ.jpeg" /></figure><h3>Introduction</h3><p>This article is designed to give an overview of the core computer science Algorithms &amp; Data Structures with a few code snippets for clarification where required.</p><h3>Big O</h3><p>Big O notation is a mathematical concept used in computer science to describe the performance or complexity of an algorithm. Specifically, it characterizes the runtime or space requirements (such as memory usage) as the size of the input data increases.</p><h4>Common Big O notations</h4><blockquote><strong>O(1)</strong>: Constant time — the algorithm takes the same amount of time to run, regardless of the input size.</blockquote><blockquote><strong>O(log n)</strong>: Logarithmic time — the runtime increases logarithmically with the input size, often seen in algorithms that halve the input at each step, like binary search.</blockquote><blockquote><strong>O(n)</strong>: Linear time — the runtime increases linearly with the input size; for example, a single loop over the data.</blockquote><blockquote><strong>O(n²)</strong>: Quadratic time — the runtime increases quadratically with the input size; for example, two nested loops over the data.</blockquote><blockquote><strong>O(n log n)</strong>: Log-linear time — this complexity often comes up in efficient sorting algorithms, such as mergesort or heapsort.</blockquote><p>Here is an example of O(n), We can tell this as we have a <strong>single loop, </strong>the loop length is determined by the input.</p><pre>function sum_char_codes(n: string): number {<br>    let sum = 0;<br>    for (let i = 0; i &lt; n.length; ++i) {<br>        sum += n.charCodeAt(i);<br>    }<br>    return sum;<br>}</pre><p>Here is an example of O(n²), We can tell this as we have a <strong>nested loop.</strong></p><pre>function sum_char_codes(n: string): number {<br>    let sum = 0;<br>    for (let i = 0; i &lt; n.length; ++i) {<br>        for (let j = 0; j &lt; n.length; ++j) {<br>            sum += charCode;<br>        }<br>    }<br>    return sum;<br>}</pre><h3>Array data structure</h3><p>An array in JavaScript is a high-level, list-like object used to be sequentially indexed and store multiple values. It can hold elements of any type, including numbers, strings, objects, or even other arrays (multidimensional arrays).</p><h4>Key points about arrays in JavaScript:</h4><blockquote><strong>Dynamic Size</strong>: Arrays in JavaScript are dynamic, meaning they can grow or shrink in size as needed.</blockquote><blockquote><strong>Zero-Indexed</strong>: The indexing of arrays starts at 0; the first element is accessed with index <em>0</em>, the second with <em>1</em>, and so on.</blockquote><blockquote><strong>Heterogeneous</strong>: JavaScript arrays can store different types of elements in the same array (heterogeneous), though it’s generally best practice to keep them homogeneous.Linear search</blockquote><p>While versatile, arrays in JavaScript also have limitations:</p><blockquote>They do not have a fixed size; managing memory efficiently can sometimes be less straightforward than with static arrays in other languages.</blockquote><blockquote>Since arrays can hold any type of data, you need to ensure type safety if your application depends on consistent data types.</blockquote><p>Arrays are fundamental to working with collections of data in JavaScript and are highly optimized for performance in modern JavaScript engines.</p><p>In terms of Big O, an array would be O(1)</p><h3>Array list</h3><p>An ArrayList is a dynamic array, which can grow or shrink in size as needed. In JavaScript, the closest equivalent to an ArrayList is the native Array object. JavaScript Arrays are automatically resizable and can contain elements of any type.</p><p>This flexibility makes arrays in JavaScript incredibly powerful and easy to use for various programming needs.</p><h4>Example of Array Usage:</h4><pre>// Creating an empty array<br>  let arrayList: string[] = [];<br><br>  // Adding elements to the end of the array<br>  arrayList.push(&quot;apple&quot;);<br>  arrayList.push(&quot;banana&quot;);<br><br>  // Adding an element to the start of the array<br>  arrayList.unshift(&quot;strawberry&quot;);<br><br>  // Accessing an element by its index<br>  console.log(arrayList[0]); // Output: &#39;strawberry&#39;<br><br>  // Removing the last element of the array<br>  let lastItem = arrayList.pop(); // &#39;banana&#39; is removed<br><br>  // Removing the first element of the array<br>  let firstItem = arrayList.shift(); // &#39;strawberry&#39; is removed<br><br>  // Adding and removing elements using splice<br>  arrayList.splice(0, 1, &quot;mango&quot;, &quot;peach&quot;); // Removes &#39;apple&#39; and adds &#39;mango&#39; and &#39;peach&#39;<br><br>  // Iterating over array elements<br>  arrayList.forEach((item) =&gt; {<br>    console.log(item);<br>  });</pre><h3>Linear search</h3><p>Linear search, also known as sequential search, is a simple algorithm that checks every element in a list or array sequentially until the desired element is found or the end of the data structure is reached.</p><h4><strong>Characteristics of Linear Search:</strong></h4><blockquote><strong>Simplicity</strong>: It’s straightforward and easy to understand.</blockquote><blockquote><strong>No Sorting Required</strong>: It can be performed on an unsorted list or array.</blockquote><blockquote><strong>Performance</strong>: Its performance is generally considered inefficient for large datasets because it works in O(n) time complexity, where n is the number of elements. This means the time taken to find an element grows linearly with the size of the dataset.</blockquote><h4>Example Linear Search:</h4><pre>function linearSearch&lt;T&gt;(arr: T[], target: T): number {<br>  for (let i = 0; i &lt; arr.length; i++) {<br>    if (arr[i] === target) {<br>      return i; // Element found, return index<br>    }<br>  }<br>  return -1; // Element not found<br>}<br><br>// Example usage:<br>const myArray: number[] = [5, 3, 15, 2, 20];<br>const target = 15;<br>const index = linearSearch&lt;number&gt;(myArray, target);<br>console.log(index);// Will output the index of the target element, if found</pre><h3>Binary search</h3><p>Binary search is an efficient algorithm for finding an item from a sorted list of items. It works by repeatedly dividing in half the portion of the list that could contain the item until you’ve narrowed down the possible locations to just one.</p><h4><strong>The basic idea behind binary search:</strong></h4><blockquote><strong>Initial Variables</strong>: You start with two pointers, one representing the start (start) of the array and the other representing the end (end). Initially, the start is at index 0, and the end is at the last index of the array.</blockquote><blockquote><strong>Check Middle</strong>: While the start is less than or equal to the end, calculate the middle index (mid) of the current start and end.</blockquote><blockquote><strong>Compare with Target</strong>: Compare the element at the mid-index with the target value.</blockquote><blockquote>If the element at mid is equal to the target, you have found the item, and you return the mid index.</blockquote><blockquote>If the element at mid is less than the target, you know the target must be in the second half of the array, so you adjust the start pointer to mid + 1.</blockquote><blockquote>Conversely, if the element at mid is greater than the target, the target must be in the first half of the array, so you adjust the end pointer to mid — 1.</blockquote><blockquote><strong>Repeat or Conclude</strong>: This process repeats, each time cutting the search area in half, until the target is found or until the start exceeds the end, which indicates that the target is not in the array.</blockquote><p>Because binary search divides the search interval in half each time, it has a time complexity of O(log n), making it much more efficient than linear search (which has a time complexity of O(n)) for large datasets. However, binary search can only be applied to a dataset that is already sorted.</p><h4>Example Binary Search:</h4><pre>  function binarySearch(array: number[], target: number): number {<br>    let start = 0;<br>    let end = array.length - 1;<br><br>    while (start &lt;= end) {<br>      let mid = Math.floor((start + end) / 2);<br><br>      if (array[mid] == target) {<br>        return mid; // target found return index<br>      } else if (array[mid] &lt; target) {<br>        start = mid + 1;<br>      } else {<br>        end = mid - 1;<br>      }<br>    }<br><br>    return -1; // target not found<br>  }<br><br>  // Example usage:<br>  const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];<br>  const target = 10;<br>  const result = binarySearch(arr, target);<br>  console.log(result);</pre><h3>Bubble sort</h3><p>Bubble sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted.</p><p>The main steps of bubble sort can be summarized as follows:</p><blockquote><strong>Start from the First Element</strong>: Begin at the start of the array.</blockquote><blockquote><strong>Compare Adjacent Elements</strong>: Compare each pair of adjacent items (A and B).</blockquote><blockquote><strong>Swap if Necessary</strong>: If A is greater than B (for ascending order), swap A and B so that the smaller item comes first.</blockquote><blockquote><strong>Move to Next Pair</strong>: Move to the next pair of items and repeat the comparison and swap if necessary.</blockquote><blockquote><strong>Complete a Pass</strong>: Continue this process for each pair of adjacent items until the end of the list is reached. This completes one pass through the list.</blockquote><blockquote><strong>Repeat Passes</strong>: After each pass, the largest element “bubbles up” to its correct position at the end of the list. Repeat the passes through the list, excluding the already sorted elements at the end, until no swaps are made on a complete pass — indicating that the list is sorted.</blockquote><p>Bubble sort has a worst-case and average time complexity of O(n²), where n is the number of items being sorted. Because of its quadratic time complexity, bubble sort is not efficient on large lists, and it’s generally only practical for small datasets or as a teaching tool to learn about sorting algorithms.</p><h4>Example Bubble sort:</h4><pre>  function bubbleSort(array: number[]): number[] {<br>    let len = array.length;<br><br>    for (let i = 0; i &lt; len; i++) {<br>      // Assume no swaps at the beginning of each pass<br>      let swapped = false;<br><br>      // Inner loop for comparing adjacent elements<br>      for (let j = 0; j &lt; len - i - 1; j++) {<br>        // If the current item is greater than the next item, swap them<br>        if (array[j] &gt; array[j + 1]) {<br>          let temp = array[j];<br>          array[j] = array[j + 1];<br>          array[j + 1] = temp;<br>          swapped = true;<br>        }<br>      }<br><br>      // If no two elements were swapped by inner loop, then break<br>      if (!swapped) {<br>        break;<br>      }<br>    }<br><br>    return array;<br>  }<br><br>  // Example usage:<br>  let numbers: number[] = [64, 34, 25, 12, 22, 11, 90];<br>  console.log(&quot;Unsorted array:&quot;, numbers);<br>  const sortedNumbers = bubbleSort(numbers);<br>  console.log(&quot;Sorted array:&quot;, sortedNumbers);</pre><h3>Linked list</h3><p>A linked list is a linear data structure where each element, often called a node, contains a value and a reference (or pointer) to the next node in the sequence. This structure allows for efficient insertion and deletion of nodes without reorganizing the entire data structure.</p><h4><strong>Key Characteristics of Linked Lists:</strong></h4><blockquote><strong>Dynamic Size</strong>: Unlike arrays, linked lists can easily grow or shrink in size; no need to define the size ahead of time.</blockquote><blockquote><strong>Sequential Access</strong>: Elements are accessed sequentially, starting from the first node (also known as the head). Random access is not possible as it is with arrays.</blockquote><blockquote><strong>Memory Efficiency</strong>: Nodes are allocated just as much memory as they need and only when they need it.</blockquote><blockquote><strong>Insertion and Deletion</strong>: Adding or removing nodes from a linked list is faster than arrays, especially for large datasets, because no shifting of elements is required.</blockquote><h4><strong>Types of Linked Lists:</strong></h4><blockquote><strong>Singly Linked List</strong>: Each node has one pointer to the next node. The last node points to null, indicating the end of the list.</blockquote><blockquote><strong>Doubly Linked List</strong>: Each node has two pointers, one to the next node and one to the previous node, making bidirectional traversal possible.</blockquote><blockquote><strong>Circular Linked List</strong>: Similar to the singly or doubly linked list, but the last node points back to the head of the list, forming a loop.</blockquote><h4>Use Cases:</h4><blockquote>When you need constant-time insertions/deletions from the list (such as in real-time computing where time predictability is critical).</blockquote><blockquote>When you don’t know how many items will be in the list. With arrays, you may need to declare their size beforehand or resize them when they reach capacity.</blockquote><h4>Downsides:</h4><blockquote>Linked lists use more memory than arrays because of the storage used by their pointers.</blockquote><blockquote>Access time for a linked list is linear, as you must traverse from the head to get to a particular node.</blockquote><blockquote>They do not allow direct access to individual elements by index like arrays do.</blockquote><p>Linked lists are a foundational data structure and form the basis for many other complex structures like stacks, queues, and associative arrays.</p><h3>Queue</h3><p>A queue is a linear data structure that follows the First In, First Out (FIFO) principle. This means that the first element added to the queue will be the first one to be removed. It’s analogous to a real-life queue, such as a line of people waiting for service where the person who comes first gets served first.</p><h4><strong>Operations:</strong></h4><blockquote><strong>Enqueue</strong>: Add an element to the end of the queue.</blockquote><blockquote><strong>Dequeue</strong>: Remove an element from the front of the queue.</blockquote><blockquote><strong>Peek/Front</strong>: Retrieve the element at the front of the queue without removing it.</blockquote><blockquote><strong>IsEmpty</strong>: Check if the queue is empty.</blockquote><blockquote><strong>IsFull</strong>: Check if the queue has reached its maximum storage capacity (mostly relevant for static-sized queues).</blockquote><h4><strong>Characteristics:</strong></h4><blockquote>Elements are added at the rear (also known as the tail) and removed from the front (also called the head).</blockquote><blockquote>It provides a fair handling of items by processing them in the order they arrive.</blockquote><h4><strong>Use Cases:</strong></h4><blockquote>Order processing systems</blockquote><blockquote>Printer task scheduling</blockquote><blockquote>CPU task scheduling</blockquote><blockquote>Handling of requests on web servers</blockquote><p>When you enqueue, an element is added to the rear. When you dequeue, an element is taken out from the front.</p><h3>Stack</h3><p>A stack is a linear data structure that follows the Last In, First Out (LIFO) principle. The last element added to the stack will be the first one removed, much like a stack of plates where you add new plates to the top and also take from the top.</p><h4>Operations:</h4><blockquote><strong>Push</strong>: Add an element to the top of the stack.</blockquote><blockquote><strong>Pop</strong>: Remove an element from the top of the stack.</blockquote><blockquote><strong>Peek/Top</strong>: Retrieve the element at the top of the stack without removing it.</blockquote><blockquote><strong>IsEmpty</strong>: Check if the stack is empty.</blockquote><blockquote><strong>IsFull</strong>: Check if the stack has reached its maximum storage capacity (pertinent for stacks with a limited size).</blockquote><h4>Characteristics:</h4><blockquote>Elements are both added and removed only from the top of the stack.</blockquote><blockquote>It provides a simple and effective way of tracking elements in a last-in, first-out manner.</blockquote><h4>Use Cases:</h4><blockquote>Undo mechanisms in software applications</blockquote><blockquote>Syntax parsing in compilers</blockquote><blockquote>Memory management</blockquote><blockquote>Call stack for function/method call management</blockquote><p>When a new element comes in, you push it onto the top. When you need to remove an element, you pop it from the top.</p><h3>Array vs Linked list</h3><p>Arrays are suitable for read-heavy operations with few insertions and deletions, while linked lists are preferred when the application involves frequent insertions and deletions.</p><h3>Array buffer</h3><p>An ArrayBuffer is a low-level binary data buffer in JavaScript that represents a fixed-length raw binary data buffer. It is part of the JavaScript Typed Array system which provides a mechanism for accessing raw binary data much like one would in lower-level programming languages.</p><h4>Key Points of ArrayBuffer:</h4><blockquote><strong>Fixed-length</strong>: Once created, you cannot change the size of an ArrayBuffer.</blockquote><blockquote><strong>Binary data</strong>: It holds raw binary data and doesn’t have any format.</blockquote><blockquote><strong>Not directly accessible</strong>: You can’t directly manipulate the contents of an ArrayBuffer; instead, you use a <em>view</em>.</blockquote><h4>Views:</h4><p>To interact with the contents of an ArrayBuffer, you need to create a &quot;view&quot;. Views are typed arrays or data views that provide a context to read and write the data in the ArrayBuffer.</p><blockquote><strong>Typed Arrays</strong> (such as Int8Array, Uint32Array, etc.) treat the buffer as an array of particular number types.</blockquote><blockquote><strong>DataViews</strong> allow for more complex interactions with the ArrayBuffer and give control over byte endian-ness.</blockquote><h4>Example of Creating and Using an ArrayBuffer:</h4><pre>// Create an ArrayBuffer of 16 bytes<br>let buffer = new ArrayBuffer(16);<br><br>// Create a view to interact with the buffer<br>let view = new Uint8Array(buffer);<br><br>// Set values in the buffer through the view<br>for (let i = 0; i &lt; view.length; i++) {<br>    view[i] = i;<br>}<br><br>console.log(view); // Output will show Uint8Array with values from 0 to 15</pre><p>ArrayBuffers are useful when dealing with raw binary data like files, streams, or complex communications protocols. They enable performance improvements for numerical computations and manipulation of bytes, such as in cryptography or audio/video processing.</p><h3>Recursion</h3><p>Recursion is a programming technique where a function calls itself to solve smaller instances of the same problem. It’s used in scenarios where a complex task can be broken down into simpler tasks with a base case.</p><h4>Key Concepts of Recursion:</h4><blockquote><strong>Base Case</strong>: The condition under which the recursion ends, preventing it from going on indefinitely.</blockquote><blockquote><strong>Recursive Case</strong>: The part of the function where it calls itself to perform the smaller or simpler task.</blockquote><h4>How Recursion Works:</h4><blockquote>Each time the recursive function is called, the old arguments are saved on the <em>call stack</em>.</blockquote><blockquote>The function keeps calling itself with new arguments until it reaches the base case.</blockquote><blockquote>When the base case is met, the function starts returning its results back up the stack.</blockquote><blockquote>The stack unwinds as each call resolves, eventually returning the final result to the initial caller.</blockquote><h4>Simple Recursive Example:</h4><pre> function factorial(n: number): number {<br>    if (n === 0 || n === 1) {<br>      // Base case<br>      return 1;<br>    } else {<br>      return n * factorial(n - 1); // Recursive case<br>    }<br>  }<br><br>  console.log(factorial(5)); // Output will be 120, as 5! = 5 * 4 * 3 * 2 * 1</pre><p>In the example above, factorial(5) recursively calls factorial(4), factorial(3), and so on, until factorial(1) or factorial(0) is reached, which returns 1, and then each call on the stack is resolved from there.</p><h4>Considerations:</h4><blockquote>Recursive solutions can be clearer and more concise than iterative ones.</blockquote><blockquote>Too many recursive calls can lead to a <em>stack overflow error</em>, if the recursion goes too deep.</blockquote><blockquote>Tail recursion optimization can help mitigate stack size issues, but JavaScript engines typically don’t support this yet.</blockquote><blockquote>It’s important to ensure that base cases are well-defined to avoid infinite recursion.</blockquote><h3>Path finding</h3><p>Path finding is the algorithmic process of finding a path between two points. In JavaScript, pathfinding can be achieved by implementing algorithms that traverse through a graph or grid to find the shortest route from the start node (point) to the end node (point).</p><h4>Common Path Finding Algorithms:</h4><blockquote><strong>Dijkstra’s Algorithm</strong>: Finds the shortest paths between nodes in a graph.</blockquote><blockquote><em>A Algorithm</em>*: Extends Dijkstra’s with a heuristic to improve performance, good for grid-based searches.</blockquote><blockquote><strong>Breadth-First Search (BFS)</strong>: Explores neighbor nodes level by level, good for finding the shortest path in unweighted graphs.</blockquote><h4>Key Elements:</h4><blockquote><strong>Graph/Grid</strong>: The representation of your map where nodes (or cells) are interconnected.</blockquote><blockquote><strong>Start Node</strong>: The starting point of the path.</blockquote><blockquote><strong>End Node</strong>: The destination point of the path.</blockquote><blockquote><strong>Costs</strong>: Sometimes moving from one node to another has a ‘cost’ associated with it.</blockquote><h4>How It Works:</h4><blockquote>Initialize the graph or grid with nodes and possible connections (edges).</blockquote><blockquote>Assign a start node and an end node.</blockquote><blockquote>Apply a pathfinding algorithm to navigate through connected nodes while minimizing cost until the end node is reached.</blockquote><blockquote>Store the visited nodes and their costs (if applicable), often using data structures like arrays, queues, or priority queues.</blockquote><h3>Quick sort</h3><p>Quicksort is a divide-and-conquer algorithm that sorts an array by selecting a ‘pivot’ element and partitioning the other elements into two sub-arrays, according to whether they are less than or greater than the pivot. The sub-arrays are then sorted recursively. This process efficiently sorts the array in place, without needing additional storage space.</p><h4>Brief description:</h4><blockquote><strong>Choose a Pivot</strong>: Select an element from the array as the pivot. Different pivot selection methods exist; a common one is picking the last element of the array for simplicity.</blockquote><blockquote><strong>Partition</strong>: Reorder the array elements so that all elements with values less than the pivot come before the pivot, while all elements with values greater than the pivot come after it. After this partitioning, the pivot is in its final position.</blockquote><blockquote><strong>Recursively Apply</strong>: Recursively apply the above steps to the sub-array of elements with smaller values and the sub-array with larger values.</blockquote><blockquote><strong>Base Case</strong>: The recursion base case occurs when the size of the array is 0 or 1, which are naturally sorted.</blockquote><blockquote><strong>In-place Sort</strong>: The original array is modified in-place to produce the sorted output.</blockquote><h4>Example:</h4><pre> function quickSort(arr: number[]): number[] {<br>    if (arr.length &lt;= 1) {<br>      return arr;<br>    }<br><br>    // Choosing the pivot as the last element of the array<br>    let pivot = arr[arr.length - 1];<br>    let left: number[] = [];<br>    let right: number[] = [];<br><br>    // Partitioning the array<br>    for (let i = 0; i &lt; arr.length - 1; i++) {<br>      if (arr[i] &lt; pivot) {<br>        left.push(arr[i]);<br>      } else {<br>        right.push(arr[i]);<br>      }<br>    }<br><br>    // Concatenating the recursive sort of left half, the pivot, and the right half<br>    return [...quickSort(left), pivot, ...quickSort(right)];<br>  }<br><br>  // Example usage:<br>  const unsortedArray = [3, 6, 8, 10, 1, 2, 1];<br>  const sortedArray = quickSort(unsortedArray);<br>  console.log(sortedArray); // Output will be the sorted array</pre><h3>Doubly Linked lists</h3><p>A doubly linked list is a data structure that consists of nodes where each node contains three items: the data, a reference to the next node in the sequence (next pointer), and a reference to the previous node (prev pointer). This allows for bidirectional traversal of the list.</p><h4><strong>Key characteristics of a doubly linked list:</strong></h4><blockquote><strong>Head</strong>: The first node in the list. The prev pointer of the head node is typically null.</blockquote><blockquote><strong>Tail</strong>: The last node in the list. The next pointer of the tail node is typically null.</blockquote><blockquote><strong>Traversal</strong>: You can traverse forward by following next pointers and backward by following prev pointers.</blockquote><blockquote><strong>Insertion</strong>: You can insert nodes efficiently at both the beginning and the end of the list, as well as in between any two nodes.</blockquote><blockquote><strong>Deletion</strong>: Nodes can be removed efficiently if you have a reference to the node that needs to be removed.</blockquote><h3>Trees</h3><p>In data structures, a tree is a hierarchical model that consists of nodes, with the first node being called the root. Each node holds its own data and may have multiple children but only one parent, except for the root which has no parent.</p><p><strong>Characteristics of Trees:</strong></p><blockquote><strong>Root</strong>: The topmost node in a tree.</blockquote><blockquote><strong>Child</strong>: A node directly connected to another node when moving away from the Root.</blockquote><blockquote><strong>Parent</strong>: The converse notion of a child.</blockquote><blockquote><strong>Siblings</strong>: Nodes with the same parent.</blockquote><blockquote><strong>Leaf</strong>: A node with no children.</blockquote><blockquote><strong>Depth</strong>: The length of the path to its root.</blockquote><blockquote><strong>Height</strong>: The length of the longest path to a leaf.</blockquote><p>A basic binary tree, where each node can have at most two children, often referred to as left and right, can be implemented in JavaScript as follows:</p><p>Here is an example of sorting a Binary tree. We will return a list of elements from the tree sorted by levels, which means the root element goes first, then root children (from left to right) are second and third, and so on.</p><pre>  class Node {<br>    value: number;<br>    left: Node | null;<br>    right: Node | null;<br><br>    constructor(<br>      value: number,<br>      left: Node | null = null,<br>      right: Node | null = null<br>    ) {<br>      this.value = value;<br>      this.left = left;<br>      this.right = right;<br>    }<br>  }<br><br>  interface Node {<br>    value: number;<br>    left?: Node;<br>    right?: Node;<br>  }<br><br>  function treeByLevels(rootNode: Node): number[] {<br>    if (!rootNode) {<br>      return [];<br>    }<br><br>    let queue: Node[] = [rootNode];<br>    let paths: number[] = [];<br><br>    while (queue.length) {<br>      const item = queue.shift();<br><br>      paths.push(item.value);<br>      if (item.left) {<br>        queue.push(item.left);<br>      }<br>      if (item.right) {<br>        queue.push(item.right);<br>      }<br>    }<br><br>    return paths;<br>  }<br><br>  const treeExample = new Node(<br>    2,<br>    new Node(8, new Node(1), new Node(3)),<br>    new Node(9, new Node(4), new Node(5))<br>  );<br><br>  console.log(treeByLevels(treeExample));<br><br>// This is how the tree looks<br>                 2<br>            8        9<br>          1  3     4   5<br>//This is the return from the function<br>[ 2, 8, 9, 1, 3, 4, 5 ]</pre><h3>Heap</h3><p>In JavaScript, a heap is a specific way to organize data that’s often used in the context of implementing priority queues and for efficient sorting algorithms like heapsort. It’s commonly referred to as a binary heap, which is a category of binary trees.</p><h4>Characteristics of a Binary Heap:</h4><blockquote><strong>Complete Binary Tree</strong>: A binary heap is a complete binary tree, meaning all levels are fully filled except possibly for the last level, which is filled from left to right.</blockquote><blockquote><strong>Heap Property</strong>: There are two kinds of binary heaps: Min-heaps and Max-heaps.</blockquote><blockquote><em>Min-heap</em>: The value of each node is greater than or equal to the value of its parent, with the minimum value at the root.</blockquote><blockquote><em>Max-heap</em>: The value of each node is less than or equal to the value of its parent, with the maximum value at the root.</blockquote><h4>Uses in JavaScript:</h4><p>In JavaScript, binary heaps aren’t provided as a built-in data structure, but you can implement them using arrays, where the children of the node at index i would be found at indexes 2*i + 1 (left child) and 2*i + 2 (right child). The parent of a node at index i can be found at index Math.floor((i-1)/2).</p><p>For instance, if you have an array representation of a min-heap like this: [1, 3, 6, 5, 9, 8], it represents the following binary tree:</p><pre>    1<br>   / \<br>  3   6<br> / \ / <br>5  9 8<br></pre><h4>Operations on Heaps:</h4><blockquote><strong>Insert</strong>: Add a new element to the heap while maintaining the heap property. This involves adding the element to the end of the array and then “heapifying up” (or percolating up) by swapping it with its parent until the heap property is restored.</blockquote><blockquote><strong>Extract-Min (Min-heap) / Extract-Max (Max-heap)</strong>: Remove and return the root element (minimum or maximum), replace it with the last element of the heap, and then “heapify down” to maintain the heap structure and property.</blockquote><h4>Implementing a Heap in JavaScript:</h4><p>You might choose to create a Heap class and include methods such as insert(), extract(), and heapify(). Since JavaScript does not have a built-in heap, those who need heap-like functionality might use libraries or frameworks that provide these structures, or they could implement their own heap based on an array structure.</p><h3>Graphs</h3><p>A graph is a non-linear data structure consisting of nodes and edges. The nodes are sometimes also referred to as vertices and the edges are lines or arcs that connect any two nodes in the graph. Graphs are used to represent networks of communication, data organization, computational devices, the flow of computation, etc.</p><h4>Components of a Graph</h4><blockquote><strong>Vertices</strong>: The entities in a graph.</blockquote><blockquote><strong>Edges</strong>: The connections between the vertices.</blockquote><blockquote><strong>Directed Graph (Digraph)</strong>: Where edges have direction.</blockquote><blockquote><strong>Undirected Graph</strong>: Where edges do not have a specific direction.</blockquote><blockquote><strong>Weighted Graph</strong>: Each edge carries a certain weight (cost).</blockquote><blockquote><strong>Unweighted Graph</strong>: Edges do not have a weight.</blockquote><h4>Types of Graphs</h4><blockquote><strong>Simple Graph</strong>: A graph without loops and multiple edges.</blockquote><blockquote><strong>Multigraph</strong>: A graph that may have multiple edges between the same pair of nodes.</blockquote><blockquote><strong>Pseudograph</strong>: A graph which may have multiple edges and loops.</blockquote><h4>Representing Graphs in JavaScript</h4><p>There are two common ways to represent graphs:</p><h4>Adjacency Matrix</h4><p>An adjacency matrix is a 2D array of size V x V where V is the number of vertices in a graph. The value of adjMatrix[i][j] is 1 if there is an edge from vertex i to j, else it is 0.</p><pre>const graph = [<br>  [0, 1, 0, 0],<br>  [1, 0, 1, 1],<br>  [0, 1, 0, 1],<br>  [0, 1, 1, 0]<br>];</pre><h4>Adjacency List</h4><p>An adjacency list represents the graph as an array of linked list. The index of the array represents the vertex and each element in its linked list represents the other vertices that form an edge with the vertex.</p><pre>const graph = [<br>  [1],       // Node 0 is connected to node 1<br>  [0, 2, 3], // Node 1 is connected to nodes 0, 2, and 3<br>  [1, 3],    // Node 2 is connected to nodes 1 and 3<br>  [1, 2]     // Node 3 is connected to nodes 1 and 2<br>];</pre><h3>Maps</h3><p>In JavaScript, a Map is a collection of keyed data items, just like an Object. However, there are important differences that make Map an attractive alternative in certain cases:</p><blockquote><strong>Keys can be of any type</strong>: Unlike objects, which typically have string or symbol keys, a Map’s keys can be any value, including functions, objects, or any primitive.</blockquote><blockquote><strong>Order of elements</strong>: The elements in a Map are ordered by the insertion order. This means when you iterate over the map, elements will be returned in the order they were added.</blockquote><blockquote><strong>Size property</strong>: A Map has a size property, which provides the number of key/value pairs in the map, making it easy to track the size without having to manually count the properties as you would with an object.</blockquote><blockquote><strong>Performance</strong>: For large sets of data, especially when adding and removing elements frequently, a Map has better performance than using an object as a hash table.</blockquote><blockquote><strong>Default keys</strong>: A Map does not contain any keys by default. It will only contain what is explicitly put into it. An object has a prototype, so it contains default keys that could collide with your own keys unless you create it as Object.create(null).</blockquote><p>Here’s a basic example of creating and using a Map:</p><pre>  // Creating a new Map<br>  let myMap = new Map();<br>  const myFunc = () =&gt; {};<br><br>  // Setting values<br>  myMap.set(&quot;keyString&quot;, &#39;value associated with &quot;keyString&quot;&#39;);<br>  myMap.set({ name: &quot;John&quot; }, &quot;value associated with John object&quot;);<br>  myMap.set(myFunc, &quot;value associated with a function&quot;);<br><br>  // Getting values<br>  console.log(myMap.get(&quot;keyString&quot;)); // Output: value associated with &quot;keyString&quot;<br>  console.log(myMap.size); // Output: 3<br><br>  // Iterating through Map<br>  for (let [key, value] of myMap) {<br>    console.log(key, value);<br>  }<br><br>  // Checking for keys and deleting<br>  if (myMap.has(&quot;keyString&quot;)) {<br>    myMap.delete(&quot;keyString&quot;);<br>  }<br><br>  console.log(myMap.get(myFunc)); // Output: value associated with a function<br><br>  // Clearing the map<br>  myMap.clear();<br>  console.log(myMap.size); // Output: 0</pre><p>Using maps can greatly improve code clarity and robustness when you need a simple key-value store with non-string keys or care about insertion order.</p><h3>LRU</h3><p>LRU stands for <em>Least Recently Used</em>, and it is a cache eviction algorithm that discards the least recently used items first when the cache reaches its capacity limit. In the context of JavaScript, an LRU cache can be implemented using a combination of data structures that support fast access, insertion, and deletion.</p><h4>Here’s a brief explanation of how an LRU cache works:</h4><blockquote><strong>Access</strong>: When an item is accessed (read or write), it becomes the most recently used (MRU) item.</blockquote><blockquote><strong>Insertion</strong>: If inserting a new item and the cache is not at capacity, it’s added as the MRU item. If the cache is full, the LRU item is removed to make space for the new one.</blockquote><blockquote><strong>Eviction</strong>: The item that has been used least recently (and thus hasn’t been accessed in the longest time) is evicted from the cache to make room for new items when necessary.</blockquote><p>To implement an efficient LRU cache in JavaScript, you might combine a Map object (as of ES6) with a doubly-linked list. The Map stores key-value pairs for quick access and constant-time updates, while the doubly-linked list maintains the order of elements based on recent use, allowing us to quickly move items to the front (MRU) or remove items from the back (LRU).</p><p>Here’s a simple conceptual implementation of an LRU Cache class:</p><pre>  class LRUCache {<br>    capacity: number;<br><br>    cache: Map&lt;any, any&gt;; // Declare the cache property<br><br>    constructor(capacity: number) {<br>      this.capacity = capacity;<br>      this.cache = new Map(); // Initialize the cache property<br>    }<br><br>    get(key: string | number) {<br>      if (this.cache.has(key)) {<br>        // Move the accessed key-value pair to the end (most recently used)<br>        const value = this.cache.get(key);<br>        this.cache.delete(key);<br>        this.cache.set(key, value);<br>        return value;<br>      }<br>      return -1;<br>    }<br><br>    put(key: string | number, value: string | number) {<br>      if (this.cache.has(key)) {<br>        // Update the existing value and move it to the end<br>        this.cache.delete(key);<br>      } else if (this.cache.size &gt;= this.capacity) {<br>        // Delete the least recently used item, which is the first one<br>        const oldestKey = this.cache.keys().next().value;<br>        this.cache.delete(oldestKey);<br>      }<br>      this.cache.set(key, value);<br>    }<br>  }<br><br>  // Usage example<br>  const cache = new LRUCache(2);<br><br>  cache.put(1, &quot;one&quot;);<br>  cache.put(2, &quot;two&quot;);<br>  console.log(cache.get(1)); // returns &quot;one&quot;<br>  cache.put(3, &quot;three&quot;); // evicts key 2<br>  console.log(cache.get(2)); // returns -1 (not found)</pre><p>This simplified version demonstrates the core concepts of an LRU cache but does not implement a full doubly-linked list to maintain the recency order. For a high-performance LRU cache, additional code would be required to handle the nodes of the linked list and their movements on access and insertion.</p><h3>Conclusion</h3><p>I hope the information I provided was useful to you; we’ve only begun to delve into this topic. Thank you for investing your time in reading it.</p><p>On my GitHub account, you’ll find several free projects ranging from Web3 implementations to constructing your own personal AI chatbot. If these topics pique your interest, feel free to explore my work by following <a href="https://github.com/gary-george"><strong>[https://github.com/gary-george]</strong></a> 🚀 .</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ed17c17e879" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build A personal AI chatbot with Node, Langchain, Typescript & React]]></title>
            <link>https://garygeorge84.medium.com/build-a-personal-ai-chatbot-with-node-langchain-typescript-react-7a71c4648ea4?source=rss-4a42073343ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a71c4648ea4</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[chatbot-development]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Gary George]]></dc:creator>
            <pubDate>Wed, 01 May 2024 22:52:26 GMT</pubDate>
            <atom:updated>2024-05-01T22:52:26.525Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ttzKjKHnrCK-EGRr9Yeh_g.jpeg" /></figure><h3>What does this project do?</h3><p>I will demonstrate how to create a chatbot capable of ingesting a resource and enabling you to retrieve data from it. For this example, I will supply a condensed version of “Romeo &amp; Juliet,” where we can extract any existing data by querying the text.</p><p>For our sample project, we will construct:</p><ul><li>A backend server using Node.js, TypeScript, Langchain, and OpenAI.</li><li>A front-end interface utilizing React and Chakra UI.</li></ul><p>Our sample project is a mono repo with both the front-end and back-end in the same repository, to get started follow the readme <a href="https://github.com/gary-george/personal_chatbot"><strong>[HERE]</strong></a>.</p><h3>The Flow</h3><p>The flow for a basic chatbot is simple</p><p>1 — Set a context we wish to search against</p><p>2 — Define our query/question</p><p>3 — Vector embed the context data &amp; the question</p><p>4 — Get a similarity search result from a vector database</p><p>5 — Pass the similarity result and our question (in plain text) to an LLM</p><p>6 — Return the result to our UI</p><h3>The Server</h3><p>Our server is a simple Node, Express, and Typescript setup.</p><p>Let’s take a look at the key areas of interest and how we will fulfill the flow.</p><p><strong>1– Set a context we wish to search against</strong></p><ul><li>in our example, we have a locally stored simplified docx version of Romeo &amp; Juliet (in production this would be a stored document in our CDN / database that we have chosen in the UI)</li></ul><p><strong>2 — Define our query/question</strong></p><ul><li>Our query is sent to the endpoint we have defined on <strong>/v1/in-memory-ai-text</strong></li></ul><p><strong>3 — Vector embed the context data &amp; the question</strong></p><ul><li>In our example project we will use the MemoryVectorStore provided by Langchain to do our vector embedding ( in production you would use a vector database such as Pinecone )</li></ul><p><strong>4 — Get a similarity search result from a vector database</strong></p><ul><li>The MemoryVectorStore will perform our similarity search and return the matches based on our query and the context data</li></ul><p><strong>5 — Pass the similarity result and our question in plain text to an LLM</strong></p><ul><li>We will use the Langchain loadQAStuffChain method and link it to Open Ai to complete our search for data by passing our results from MemoryVectorStore and passing in the plain text query</li></ul><p><strong>6 — Return the result to our UI</strong></p><ul><li>Finally, once we have the answer to our query we return it from the end-point</li></ul><p>All of the magic happens within our <strong>server/routes/textloader.ts </strong>file.</p><pre>export default async (question = &quot;&quot;, filePath = &quot;&quot;) =&gt; {<br>  const fileExtension = filePath.split(&quot;.&quot;).pop();<br>  let loader;<br><br>  if (fileExtension === &quot;docx&quot;) {<br>    loader = new DocxLoader(filePath);<br>  } else if (fileExtension === &quot;txt&quot;) {<br>    loader = new TextLoader(filePath);<br>  } else if (fileExtension === &quot;pdf&quot;) {<br>    loader = new PDFLoader(filePath, {<br>      splitPages: false,<br>    });<br>  } else {<br>    return &quot;unsupported file type&quot;;<br>  }<br><br>  const docs = await loader.load();<br><br>  const vectorStore = await MemoryVectorStore.fromDocuments(<br>    docs,<br>    new OpenAIEmbeddings()<br>  );<br><br>  const searchResponse = await vectorStore.similaritySearch(question, 1);<br>  const textRes = searchResponse.map((item) =&gt; item?.pageContent).join(&quot;\n&quot;);<br>  const llm = new OpenAI({ modelName: &quot;gpt-4&quot; });<br>  const chain = loadQAStuffChain(llm);<br><br>  const result = await chain.invoke({<br>    input_documents: [new Document({ pageContent: `${textRes}` })],<br>    question,<br>  });<br><br>  console.log(`\n\n Question: ${question}`);<br>  console.log(`\n\n Answer: ${result.text}`);<br>  return result.text;<br>};</pre><p>A couple of things to note, If you are using a docx file you need to install <a href="https://www.npmjs.com/package/mammoth"><em>mammoth</em></a>, If you are using a PDF file you will need to install <a href="https://www.npmjs.com/package/pdf-parse"><em>pdf-parse</em></a>. Both of these are already in our dependencies. They are not added automatically by Langchain.</p><p>We trigger the above function from a simple GET request, in the request, we pass the question as a query string but have hardcoded the locally stored document that will be used for the context.</p><p>To further extend this you could store your documents in something like S3 and pass in a parameter identifying the document required for the context.</p><pre>export const inMemoryChat = async (req: Request, res: Response) =&gt; {<br>  const question = req.query.question as string;<br>  const filePath = &quot;files/romeo&amp;juliet.docx&quot;;<br><br>  const result = await TextLoader(question, filePath);<br><br>  res.status(200).json({<br>    question,<br>    answer: result,<br>  });<br>};</pre><p>We can call the backend from a rest client such as <a href="https://insomnia.rest/"><strong>Insomnia</strong></a> or <a href="https://www.postman.com/"><strong>Postman</strong></a><strong>.</strong></p><p>Here is the result when calling our Rest API from a rest client.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LibofJ3Wcv-bd73k9UYMcg.png" /></figure><h3>The Front-end</h3><p>The front end can be anything, all of the work is facilitated by the back end.</p><p>I have provided a small application using React &amp; Chakra UI, which provides a user interface for interacting with the back end.</p><p>When you load up the app you will see this screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-T5WbaYn4EAt3ucOSUnK5w.png" /></figure><p>From here you can try out our chatbot, As mentioned above the scope of the queries you can make is restricted to the simplified docx version of Romeo &amp; Juliet that we have stored locally on our server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TctAS5G_G12q_RSJqJ5NCA.png" /></figure><p>From here you can ask questions and see real-time answers returned from our server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qLGlf3LEqOC59poFKIP7DA.png" /></figure><p>This is a great place to leave this project, ready to be explored and extended. 🚀</p><h3>Project code 👨‍💻</h3><p>The source code for this project is available for free <a href="https://github.com/gary-george/personal_chatbot"><strong>[HERE]</strong></a>.</p><p>This is a good-to-go project that can help you get a real feel for how everything works.</p><h3>Helpful Links</h3><ul><li><a href="https://v2.chakra-ui.com/">Chakra UI - A simple, modular and accessible component library that gives you the building blocks you need to build your React applications.</a></li><li><a href="https://js.langchain.com/docs/modules/chains/document/stuff">Stuff | 🦜️🔗 Langchain</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a71c4648ea4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create a Web3 Project with Typescript]]></title>
            <link>https://garygeorge84.medium.com/create-a-web3-project-with-typescript-a5dcf27ee5e2?source=rss-4a42073343ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5dcf27ee5e2</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript-with-react]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Gary George]]></dc:creator>
            <pubDate>Fri, 26 Apr 2024 21:51:05 GMT</pubDate>
            <atom:updated>2024-04-28T18:57:28.992Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kFxJzQhuJvSBmQhsbAIheA.jpeg" /></figure><h3>What does this project do? 🤖</h3><p>This project allows a user to input any ‘Ethereum Mainnet Contract Address’ and retrieve information &amp; transaction history for it.</p><p>This is built to be a helpful project for people trying to get started building Web3 projects.</p><p>A demo version of the project is available <a href="https://web3-contract-explorer-ruby.vercel.app/"><strong>[HERE]</strong></a></p><h3>What technology has been used? 💻</h3><pre>- Next Js<br>- Typescript<br>- Web3Modal<br>- Ethers</pre><h3>Next JS &amp; Typescript 👾</h3><p>This project is built using Next JS &amp; Typescript.</p><p><strong>Next JS</strong></p><p>Next JS offers great out-of-the-box functionality for advanced projects targeting SEO or pre-rendering capabilities. With the foundations of Next JS in your toolkit, you can supercharge your site and get an edge over vanilla React applications.</p><p>For information on NextJS click<a href="https://nextjs.org/"><strong> [HERE]</strong></a>.</p><p><strong>Typescript</strong></p><p>At this point, Typescript is the de facto standard for javascript applications for many reasons such as:</p><ul><li><strong>Type Safety</strong>: TypeScript provides static type checking, which can catch errors at compile time rather than runtime, leading to fewer bugs in production.</li><li><strong>Improved Developer Experience</strong>: Features like auto-completion, interface support, and detailed error messages enhance developer productivity and code maintainability.</li><li><strong>Easier Refactoring</strong>: TypeScript’s strong typing system makes refactoring large codebases safer and more predictable by ensuring changes do not introduce new errors.</li><li><strong>Better Readability</strong>: Type annotations and interfaces help document the code, making it clearer what shapes of data are being passed around within the React components.</li><li><strong>Community and Ecosystem Support</strong>: With TypeScript’s growing popularity, many libraries, including those used in the React ecosystem, offer first-class TypeScript support.</li></ul><p>For further information on Typescript in Next JS click <a href="https://nextjs.org/docs/pages/building-your-application/configuring/typescript"><strong>[HERE]</strong></a>.</p><h3>Web3Modal 🔥</h3><p>We use Web3Modal in this project to allow a user to connect their wallet to our application, while we don&#39;t do any real interaction with the user&#39;s wallet, it is here to show you how you may facilitate this interaction.</p><p>There are a couple of steps that you need to do to use the Web3Modal connect wallet feature.</p><p>1 — Create a project ID at <a href="https://cloud.walletconnect.com/">https://cloud.walletconnect.com</a></p><p>2 — Create a config file in your application</p><pre>&quot;use client&quot;;<br><br>import { createWeb3Modal, defaultConfig } from &quot;@web3modal/ethers/react&quot;;<br><br>// Create your own projectId at https://cloud.walletconnect.com<br>const projectId = process.env.NEXT_PUBLIC_WALLET_CONNECT_PROJECT_ID;<br><br>const mainnet = {<br>  chainId: 1,<br>  name: &quot;Ethereum&quot;,<br>  currency: &quot;ETH&quot;,<br>  explorerUrl: &quot;https://etherscan.io&quot;,<br>  rpcUrl: &quot;https://cloudflare-eth.com&quot;,<br>};<br><br>const metadata = {<br>  name: &quot;My Website&quot;,<br>  description: &quot;My Website description&quot;,<br>  url: &quot;http://localhost&quot;,<br>  icons: [&quot;https://avatars.mywebsite.com/&quot;],<br>};<br><br>const ethersConfig = defaultConfig({<br>  metadata,<br>  enableEIP6963: true,<br>  enableInjected: true,<br>  enableCoinbase: true,<br>  rpcUrl: &quot;...&quot;,<br>  defaultChainId: 1,<br>});<br><br>createWeb3Modal({<br>  ethersConfig,<br>  chains: [mainnet],<br>  projectId: `${projectId}`,<br>  enableAnalytics: true,<br>  enableOnramp: true,<br>});<br><br>export function Web3Modal({ children }: { children: React.ReactNode }) {<br>  return children;<br>}</pre><p>3 — Import the custom Web3Modal component from your config file, and wrap it around any component you wish to have access to the functionality.</p><pre>import { Web3Modal } from &quot;../context/web3modal&quot;;<br><br>...<br><br>export default function RootLayout({<br>  children,<br>}: Readonly&lt;{<br>  children: React.ReactNode;<br>}&gt;) {<br>  return (<br>    &lt;html lang=&quot;en&quot;&gt;<br>      &lt;body className={inter.className}&gt;<br>        &lt;Web3Modal&gt;{children}&lt;/Web3Modal&gt;<br>      &lt;/body&gt;<br>    &lt;/html&gt;<br>  );<br>}</pre><p>4 — Use the connect wallet button</p><p>Now you can use this anywhere inside your nested components.</p><pre>&lt;w3m-button /&gt;</pre><p>For information on integrating Web3Modal with a NextJS application click <a href="https://docs.walletconnect.com/web3modal/nextjs/about"><strong>[HERE]</strong></a>.</p><h3>Ethers 👽</h3><p>We use Ethers to talk to the blockchain, Ethers is a library for interacting with the Ethereum Blockchain and its ecosystem.</p><p>The Ethers library essentially allows us to get the data for an inputted contract address.</p><p>An example in this project where Ethers is used can be found in the <strong>getData</strong> function.</p><p>You can see below the methods we use from the Ethers library to talk to a specified contract and retrieve information from the Blockchain.</p><pre>import { BrowserProvider, Contract, formatUnits } from &quot;ethers&quot;;<br>import { Eip1193Provider } from &quot;ethers/providers&quot;;<br><br>import { ABI } from &quot;@/helpers/defaultABI&quot;;<br><br>type getDataReturnType = {<br>  userBalance: string;<br>  totalSupply: string;<br>  name: string;<br>  symbol: string;<br>};<br><br>export const getData = async (<br>  isConnected: boolean,<br>  address: `0x${string}` | undefined,<br>  contractAddress: `0x${string}`,<br>  walletProvider: Eip1193Provider | undefined<br>): Promise&lt;getDataReturnType&gt; =&gt; {<br>  if (!isConnected || !walletProvider) throw Error(&quot;User disconnected&quot;);<br><br>  const ethersProvider = new BrowserProvider(walletProvider);<br>  const signer = await ethersProvider.getSigner();<br>  const contract = new Contract(contractAddress, ABI, signer);<br>  const userBalance = await contract.balanceOf(address);<br>  const totalSupply = await contract.totalSupply();<br>  const symbol = await contract.symbol();<br>  const name = await contract.name();<br><br>  return {<br>    userBalance: formatUnits(userBalance, 18),<br>    totalSupply: totalSupply.toString(),<br>    name,<br>    symbol,<br>  };<br>};</pre><p>For further information on Ethers click <a href="https://docs.ethers.org/v6/"><strong>[HERE]</strong></a>.</p><h3>Transaction History 📚</h3><p>We can get the transaction history of a contract by using the Ethers library and extending one of the provided classes.</p><p><em>This snippet was found on stack overflow.</em></p><pre>import { EtherscanProvider } from &quot;ethers&quot;;<br>import { BlockTag, Networkish } from &quot;ethers/providers&quot;;<br><br>export class MyEtherscanProvider extends EtherscanProvider {<br>  constructor(networkish?: Networkish, apiKey?: string) {<br>    super(networkish, apiKey);<br>  }<br><br>  async getHistory(<br>    address: string,<br>    startBlock?: BlockTag,<br>    endBlock?: BlockTag<br>  ): Promise&lt;Array&lt;any&gt;&gt; {<br>    const params = {<br>      action: &quot;txlist&quot;,<br>      address,<br>      startblock: startBlock == null ? 0 : startBlock,<br>      endblock: endBlock == null ? 99999999 : endBlock,<br>      sort: &quot;desc&quot;,<br>    };<br><br>    return this.fetch(&quot;account&quot;, params);<br>  }<br>}</pre><h3>Tests 🧪</h3><p>Some example Testing Library specs have been written and can be found in the <strong>__tests__ </strong>directory at the root of the project.</p><p>We have 2 tests to help you get started, one for when a user has connected their wallet and one for when a user is not connected.</p><p>The testing library allows us to examine how our React components render and assert on different things such as interactions with buttons or that correct text is displayed.</p><p>For more information on the testing library click <a href="https://testing-library.com/docs/react-testing-library/example-intro"><strong>[HERE]</strong></a>.</p><h3>Project URL ✈️</h3><p>A demo version of the project is available <a href="https://web3-contract-explorer-ruby.vercel.app/"><strong>[HERE]</strong></a></p><h3>Project code 👨‍💻</h3><p>The source code for this project is available for free <a href="https://github.com/gary-george/web3-contract-explorer"><strong>[HERE]</strong></a>.</p><p>This is a good-to-go project that can help you get a real feel for how everything works.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5dcf27ee5e2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Guide to creating your own NFT with Javascript & Solidity – UPDATED to include video guide -(Part…]]></title>
            <link>https://medium.com/coinmonks/guide-to-creating-your-own-nft-with-javascript-solidity-part-3-of-3-6dae8da7e3f?source=rss-4a42073343ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/6dae8da7e3f</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[truffle-suite]]></category>
            <category><![CDATA[nft-collectibles]]></category>
            <category><![CDATA[nft]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Gary George]]></dc:creator>
            <pubDate>Sat, 11 Sep 2021 14:13:20 GMT</pubDate>
            <atom:updated>2023-01-03T10:17:15.293Z</atom:updated>
            <content:encoded><![CDATA[<h3>Guide to creating your own NFT with Javascript &amp; Solidity – UPDATED to include video guide -🌎(Part 3 of 3)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*85vbrfRqI57Vf_jDxJgP1Q.png" /></figure><p>In Part 2 <a href="https://garygeorge84.medium.com/guide-to-creating-your-own-nft-with-javascript-solidity-part-2-of-3-ceaa1cb2412a"><strong>[LINK]</strong></a> we interacted with our contract and prepared our content to be minted, Here we are going to finish off the process and mint an NFT.</p><h3>What are Gas Fees?</h3><p>“Gas fees are <strong>payments made by users to compensate for the computing energy required to process and validate transactions on the Ethereum blockchain</strong>. … A higher gas limit means that you must do more work to execute a transaction using ETH or a smart contract.”</p><p>Basically every transaction you make on the blockchain comes at a cost, The cost varies but here is a real life example i have faced.</p><p>The price for me to mint 1000 NFTs onto the Ethereum Mainnet was going to cost me the equivalent of <strong>£3000, </strong>I knew instantly this was out of my budget for a simple pet project so i looked further a field.</p><p>Now this is out of the scope of this article but i decided to Mint my NFTs on the Polygon Mainnet (see <a href="https://polygon.technology/"><strong>[HERE]</strong></a> for what this is). The price it ended up costing me to mint all of the NFTs on Polygon was £0.30, literally 30p ! 🚀</p><p>So be careful when doing such a task and always experiment on the <a href="https://docs.ethhub.io/using-ethereum/test-networks/"><strong>[TestNets]</strong></a><strong> </strong>first.</p><h3>Minting your content</h3><p>Ok, so you are all set up, the front end website is hooked up to your contract, your assets have been created and pinned to IPFS. Its time to MINT your NFTs.</p><p>You will need to create a script and then run the script using the <a href="https://www.trufflesuite.com/docs/truffle/reference/truffle-commands"><strong>[TRUFFLE CLI]</strong></a>, here is the command i use to run my minting script from the command line:</p><pre>truffle exec src/utils/mint.js --network polygon</pre><p>The flag — network polygon points to the network details for polygon network which i added to my truffle-config.js.</p><p>it will look something like this:</p><pre>...</pre><pre>polygon: {</pre><pre> provider: () =&gt;</pre><pre> new HDWalletProvider(</pre><pre> privateKeys.split(&quot;,&quot;),</pre><pre> `https://polygon-mainnet.infura.io/v3/${process.env.INFURA_PROJECT_ID}`</pre><pre>),</pre><pre> network_id: 137,</pre><pre> confirmations: 2,</pre><pre> timeoutBlocks: 200,</pre><pre> skipDryRun: true,</pre><pre> chainId: 137,</pre><pre>},<br>...<br></pre><p>You will need to sign up to <a href="https://infura.io/"><strong>[INFURA]</strong></a> or similar to get a <strong>Project ID</strong> for an ethereum node on your desired network.</p><p>Here is a valid example of a mint script that you can call from the above command :</p><pre>//THIS IS THE PATH TO YOUR ABI FILE<br>const NFT = artifacts.require(&quot;NFT&quot;);</pre><pre>module.exports = <em>async</em> function (callback) {</pre><pre>   // THIS IS CHECKING THAT THE SCRIPT CAN FIND YOUR CONTRACT<br>   const nft = await NFT.deployed();<br></pre><pre>   //THIS WILL MINT AN NFT<br>   try {</pre><pre>       await nft.mint(PATH_TO_UR_METADATA_FILE_ON_IPFS);</pre><pre>    } catch (e) {</pre><pre>       console.log(&quot;failed&quot;, e);</pre><pre>    }</pre><pre>}</pre><p>Wow!, how simple was that 🦄.</p><h3>Buying an NFT</h3><p>For a user of your website to purchase an NFT, they must first connect their wallet and secondly they must be on the correct network.</p><p>If they are on a network which does not have your contract deployed then they will receive an error message.</p><p>The below snippet is an example of a function call in javascript that can facilitate the transfer of ownership of a token (purchase an NFT).</p><pre>const buyNFT = <em>async</em> (account, contract, showModal) =&gt; {</pre><pre>  //THE TOKEN ID TO PURCHASE<br>  const tokenID = 1;<br>  const accountAddress = THE_USERS_WALLET_ADDRESS;</pre><pre>  // ONE THING TO NOTE THE PRICE WILL BE IN WEI <br>  // -&gt; 18 DECIMAL PLACES<br>  // THE BELOW WORKS OUT AT 0.021 Eth<br>  const price = 21000000000000000;</pre><pre>  //THE ACTUAL CALL TO THE CONTRACT FOR PURCHASE</pre><pre>  await contract.methods<br>  .buy(id)<br>  .send({ from: accountAddress, value: price })<br>  .on(&quot;receipt&quot;, <em>async</em> () =&gt; {<br>     console.log(`You&#39;ve received the NFT with ID: ${id}`);<br>  }<br>  .on(&quot;error&quot;, (error) =&gt; {<br>     console.log(`error in purchase- ${error}`);<br>  }</pre><pre>}</pre><h3>Verifying NFT ownership</h3><p>Excellent, we are at the final hurdle.</p><p>How can you verify ownership of an NFT? Well we have actually already been over this.</p><p>Take a look at the code snippet i shared in <a href="https://garygeorge84.medium.com/guide-to-creating-your-own-nft-with-javascript-solidity-part-2-of-3-ceaa1cb2412a"><strong>[PART2]</strong></a>. The function to focus your attention on is :</p><pre>const owner = await contract.methods.ownerOf(tokenID).call();</pre><p>The above function will go off to the contract on the blockchain and return the owners wallet address.</p><p>All NFTs have an owner whether they have been purchased or not, the initial owner is the contracts address, upon a purchase the owner gets transferred to the users wallet address.</p><h3>Free Video [Code Walkthrough]</h3><p>I have recorded a video walking through the boilerplate code <a href="https://www.youtube.com/watch?v=F0xD1DK3pe4&amp;ab_channel=G">[LINK]</a>. I really hope this helps other developers out who are looking to go into Blockchain development.</p><h3>Crypto Ghoulz</h3><p>For research into this topic i created my own blockchain based website on the polygon network, which allows users to purchase NFTs, check it out and if your feeling spicy purchase one of my NFTs. <a href="https://cryptoghoulz.com/">https://cryptoghoulz.com</a> .</p><p>If you have any questions surrounding <strong>Crypto Ghoulz</strong> get in touch via twitter.</p><h3>Project Code</h3><p>If you want to get started on this you can find a boiler plate repo <a href="https://github.com/gary-george/nft-react-boilerplate"><strong>[HERE]</strong></a>.</p><p>This is a good to go project that can help you get a real feel for how everything works.</p><h3>Links</h3><p><strong>Video Guide:</strong> <a href="https://youtu.be/F0xD1DK3pe4">https://youtu.be/F0xD1DK3pe4</a></p><p><strong>Boilerplate:</strong> <a href="https://github.com/gary-george/nft-react-boilerplate">https://github.com/gary-george/nft-react-boilerplate</a></p><p><strong>Crypto Ghoulz:</strong> <a href="https://cryptoghoulz.com/">https://cryptoghoulz.com/</a></p><p><strong>Blog Posts:</strong></p><p><strong>Part 1 of 3: </strong><a href="https://medium.com/coinmonks/guide-to-creating-your-own-nft-with-javascript-solidity-part-1-of-3-7909b80fae94">https://medium.com/coinmonks/guide-to-creating-your-own-nft-with-javascript-solidity-part-1-of-3-7909b80fae94</a></p><p><strong>Part 2 of 3: </strong><a href="https://medium.com/coinmonks/guide-to-creating-your-own-nft-with-javascript-solidity-part-2-of-3-ceaa1cb2412a">https://medium.com/coinmonks/guide-to-creating-your-own-nft-with-javascript-solidity-part-2-of-3-ceaa1cb2412a</a></p><p><strong>Part 3 of 3: </strong><a href="https://medium.com/coinmonks/guide-to-creating-your-own-nft-with-javascript-solidity-part-3-of-3-6dae8da7e3f">https://medium.com/coinmonks/guide-to-creating-your-own-nft-with-javascript-solidity-part-3-of-3-6dae8da7e3f</a></p><h3>Summary</h3><p>In this collection of posts, we have gone through the entire process of creating your own contract, minting and purchasing. I hope this helps clear up some of the questions you may have had in regards to the mystery&#39;s of the NFT world.</p><blockquote>Join <a href="https://t.me/coincodecap">Coinmonks Telegram Channel</a> and learn about crypto trading and investing.</blockquote><p><strong>Also, Read</strong></p><ul><li><a href="https://medium.com/coinmonks/youhodler-vs-coinloan-vs-hodlnaut-b1050acde55a">YouHodler vs CoinLoan vs Hodlnaut</a> | <a href="https://blog.coincodecap.com/cryptohopper-vs-haasbot">Cryptohopper vs HaasBot</a></li><li><a href="https://blog.coincodecap.com/binance-vs-kraken">Binance vs Kraken</a> | <a href="https://blog.coincodecap.com/pionex-dca-bot">Dollar-Cost Averaging Trading Bot</a></li><li><a href="https://medium.com/coinmonks/buy-bitcoin-in-india-feb50ddfef94">How to buy Bitcoin in India?</a> | <a href="https://medium.com/coinmonks/wazirx-review-5c811b074f5b">WazirX Review</a> | <a href="https://blog.coincodecap.com/bitmex-review">BitMEX Review</a></li><li><a href="https://blog.coincodecap.com/bitcoin-taproot">Bitcoin Taproot</a> | <a href="https://blog.coincodecap.com/bitso-review">Bitso Review</a> | <a href="https://medium.com/coinmonks/bitcoin-credit-card-bc8ab6f377c6">Top 6 Bitcoin Credit Card</a></li><li><a href="https://blog.coincodecap.com/gemini-vs-coinbase">Gemini vs Coinbase</a> | <a href="https://blog.coincodecap.com/kraken-vs-coinbase">Coinbase vs Kraken</a> | <a href="https://blog.coincodecap.com/coinspot-vs-coinjar">CoinJar vs CoinSpot</a></li><li><a href="https://medium.com/coinmonks/bitcoin-exchange-in-india-7f1fe79715c9">Indian crypto exchange</a>| <a href="https://medium.com/coinmonks/bitcoin-savings-account-e65b13f92451">Bitcoin Savings Account</a> | <a href="https://medium.com/coinmonks/paxful-review-4daf2354ab70">Paxful Review</a></li><li><a href="https://medium.com/coinmonks/leveraged-token-3f5257808b22">Leveraged Token</a> | <a href="https://medium.com/coinmonks/crypto-exchange-dd2f9d6f3769">Best Crypto Exchange</a> | <a href="https://medium.com/coinmonks/ascendex-review-53e829cf75fa">AscendEX Review</a></li><li><a href="https://medium.com/coinmonks/godex-io-review-7366086519fb">Godex.io Review</a> | <a href="https://medium.com/coinmonks/invity-review-70f3030c0502">Invity Review</a> | <a href="https://blog.coincodecap.com/bitforex-review">BitForex Review</a> | <a href="https://medium.com/coinmonks/hitbtc-review-c5143c5d53c2">HitBTC Review</a></li><li><a href="https://medium.com/coinmonks/binance-fees-8588ec17965">Binance Fees</a> | <a href="https://medium.com/coinmonks/botcrypto-review-2021-build-your-own-trading-bot-coincodecap-6b8332d736c7">Botcrypto Review</a> | <a href="https://blog.coincodecap.com/crypto-com-alternatives">Crypto.com Alternatives</a></li><li><a href="https://blog.coincodecap.com/trading-signal">What are the Trading Signals?</a> | <a href="https://blog.coincodecap.com/bitstamp-coinbase">Bitstamp vs Coinbase</a></li><li><a href="https://blog.coincodecap.com/profitfarmers-review">ProfitFarmers Review</a> | <a href="https://blog.coincodecap.com/cornix-trading-bot">How to use Cornix Trading Bot</a></li><li><a href="https://medium.com/coinmonks/mxc-exchange-review-3af0ec1cba8c">MXC Exchange Review</a> | <a href="https://blog.coincodecap.com/pionex-vs-binance">Pionex vs Binance</a> | <a href="https://blog.coincodecap.com/pionex-arbitrage-bot">Pionex Arbitrage Bot</a></li><li><a href="https://medium.com/coinmonks/my-experience-with-crypto-copy-trading-d6feb2ce3ac5">My Experience with Crypto Copy Trading</a> | <a href="https://medium.com/coinmonks/coinbase-review-6ef4e0f56064">Coinbase Review</a></li><li><a href="https://blog.coincodecap.com/coinflex-review">CoinFLEX Review</a> | <a href="https://blog.coincodecap.com/aex-exchange-review">AEX Exchange Review</a> | <a href="https://blog.coincodecap.com/upbit-review">UPbit Review</a></li><li><a href="https://blog.coincodecap.com/ascendex-margin-trading">AscendEx Margin Trading</a> | <a href="https://blog.coincodecap.com/bitfinex-staking">Bitfinex Staking</a> | <a href="https://blog.coincodecap.com/bitflyer-review">bitFlyer Review</a></li><li><a href="https://blog.coincodecap.com/sparrow-exchange-review">Sparrow Exchange Review</a> | <a href="https://blog.coincodecap.com/nash-exchange-review">Nash Exchange Review</a></li><li><a href="https://medium.com/coinmonks/cryptocurrency-savings-accounts-be3bc0feffbf">Cryptocurrency Savings Accounts</a> | <a href="https://blog.coincodecap.com/staking-crypto">Staking Crypto</a></li><li><a href="https://medium.com/coinmonks/bigone-exchange-review-64705d85a1d4">BigONE Exchange Review</a> | <a href="https://blog.coincodecap.com/cex-io-review">CEX.IO Review</a> | <a href="https://medium.com/coinmonks/swapzone-review-crypto-exchange-data-aggregator-e0ad78e55ed7">Swapzone Review</a></li><li><a href="https://medium.com/coinmonks/bitcoin-margin-trading-exchange-bcbfcbf7b8e3">Best Bitcoin Margin Trading</a>| <a href="https://blog.coincodecap.com/bityard-margin-trading">Bityard Margin Trading</a></li><li><a href="https://medium.com/coinmonks/crypto-margin-trading-exchanges-428b1f7ad108">Crypto Margin Trading Exchanges</a> | <a href="https://medium.com/coinmonks/earn-bitcoin-6e8bd3c592d9">Earn Bitcoin</a> | <a href="https://blog.coincodecap.com/mudrex-invest-review-the-best-way-to-invest-in-crypto">Mudrex Invest</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6dae8da7e3f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/guide-to-creating-your-own-nft-with-javascript-solidity-part-3-of-3-6dae8da7e3f">Guide to creating your own NFT with Javascript &amp; Solidity – UPDATED to include video guide -🌎(Part…</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Guide to creating your own NFT with Javascript & Solidity – UPDATED to include video guide –…]]></title>
            <link>https://medium.com/coinmonks/guide-to-creating-your-own-nft-with-javascript-solidity-part-2-of-3-ceaa1cb2412a?source=rss-4a42073343ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/ceaa1cb2412a</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[nft]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[nft-collectibles]]></category>
            <dc:creator><![CDATA[Gary George]]></dc:creator>
            <pubDate>Thu, 09 Sep 2021 15:02:29 GMT</pubDate>
            <atom:updated>2023-01-03T10:16:44.975Z</atom:updated>
            <content:encoded><![CDATA[<h3>Guide to creating your own NFT with Javascript &amp; Solidity – UPDATED to include video guide – 👾(Part 2 of 3)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Gv-f5L2_lMpAyda4MsvTAg.png" /></figure><p>In Part 1<a href="https://garygeorge84.medium.com/guide-to-creating-your-own-nft-with-javascript-solidity-part-1-of-3-7909b80fae94"><strong>[LINK]</strong></a> we were introduced to the core concepts of NFTs and how to create your own contract, now its time to interact with your new contract.</p><h3>Interacting with your contract 💻</h3><p>Once your contract has been deployed you will need some way of interacting with it (Remember to review <a href="https://www.youtube.com/watch?v=CgXQC4dbGUE&amp;t=78s&amp;ab_channel=DappUniversity"><strong>[this]</strong></a> video if you need help deploying).</p><p>To interact you need to connect your website to the blockchain, this is not as scary as it sounds. To connect your website you need to use a library called <a href="https://web3js.readthedocs.io/en/v1.5.2/"><strong>[WEB3JS]</strong></a><strong>.</strong></p><p>As you should now be aware, once you successfully compile and migrate your contract with <a href="https://www.trufflesuite.com/"><strong>[Truffle]</strong></a> you will have an ABI file in JSON format for your contract.</p><p>It is the abi.json file that you will use to connect to your contract, The ABI file contains every piece of information about your contract , One important piece of information it has, is its address on the blockchain.</p><p>Without knowing the address there is no way of interacting.</p><h3>Web3 JS</h3><p>Here is a ready to go example of connecting to your contract using <a href="https://web3js.readthedocs.io/en/v1.5.2/"><strong>[Web3]</strong></a><strong> </strong>from a React based website. ( Once again if you are feeling really lost refer to <a href="https://www.youtube.com/watch?v=CgXQC4dbGUE&amp;t=78s&amp;ab_channel=DappUniversity"><strong>[this]</strong></a> video ) .</p><p>I like to use <a href="https://www.npmjs.com/package/web3modal"><strong>[Web3Modal]</strong></a> in conjunction with Web3 JS, this allows us to easily connect a users wallet to our site.</p><ul><li>Below is a snippet for a React project using Hooks.</li><li>I have commented the code where it is important</li></ul><pre>import React, { useEffect} from &quot;react&quot;;<br>import Web3 from &quot;web3&quot;;<br>import Web3Modal from &quot;web3modal&quot;;<br>import Contract from &quot;../truffle/abis/NFT.json&quot;;</pre><pre>const loadWeb3 = async()=&gt;{</pre><pre> //THIS ALLOWS YOU TALK TO BLOCKCHAIN<br>  const web3Modal = new Web3Modal({<br>    network: &quot;mainnet&quot;, <em>// optional<br>    </em>cacheProvider: true, <em>// optional<br>    </em>providerOptions: {}, <em>// required<br>  </em>});<br>  const provider = await web3Modal.connect();<br>  const web3 = new Web3(provider);<br>  const netId = await web3.eth.net.getId();</pre><pre>  //THIS WILL LOAD YOUR CONTRACT FROM BLOCKCHAIN<br>  const contract = new web3.eth.Contract(<br>    Contract.abi,<br>    Contract.networks[netId].address<br>  );</pre><pre>  // FROM HERE YOU CAN NOW QUERY YOUR CONTRACT FOR DATA<br>  // HERE ARE A FEW EXAMPLES</pre><pre>  // THE TOKEN ID YOU WANT TO QUERY<br>  const tokenID = 1;</pre><pre>  // GET THE AMOUNT OF NFTs MINTED <br>  const totalSupply = await contract.methods.totalSupply().call();</pre><pre>  // GET THE TOKEN URI<br>  // THE URI IS THE LINK TO WHERE YOUR JSON DATA LIVES<br>  const uri = await contract.methods.tokenURI(tokenID).call();</pre><pre>  // GET THE OWNER OF A SPECIFIC TOKEN<br>  const owner = await contract.methods.ownerOf(tokenID).call();</pre><pre>  // CHECK IF A SPECIFIC TOKEN IS SOLD<br>  const sold = await contract.methods.sold(tokenID).call();</pre><pre>  // GET PRICE OF A SPECIFIC TOKEN<br>  const price = await contract.methods.price(tokenID).call();</pre><pre>}</pre><pre>const ExampleComponent = ()=&gt;{</pre><pre>useEffect(()=&gt;{<br>    loadWeb3();<br>},[])</pre><pre>return (&lt;p&gt;My component&lt;/p&gt;)</pre><pre>}</pre><pre>export default ExampleComponent</pre><h3>IPFS?</h3><p>“IPFS is <strong>a peer-to-peer (p2p) storage network</strong>. Content is accessible through peers located anywhere in the world, that might relay information, store it, or do both. IPFS knows how to find what you ask for using its content address rather than its location.”</p><p>Ok so you now have the code for interacting with your contract 👆, but at the moment you don’t have any tokens minted, or any items ready for minting.</p><p>I like to use <a href="https://www.npmjs.com/package/ipfs-http-client"><strong>[ipfs-http-client]</strong></a> when i wish to add items to IPFS, Its really simple to use.</p><p>After successfully adding an item to IPFS it will return a CID, the CID is your unique hash and allows you to find your image on IPFS. You can optionally pin your CIDs , this stops your uploads being garbage collected and removed from IPFS</p><p>The best practice for NFTs is :</p><ul><li>add your image to IPFS</li><li>create a basic JSON file which contains at least 3 keys (name , description, image)</li><li>The image key will be the full URL to the item you added to IPFS</li><li>add your meta data file to IPFS</li><li>Pin the CIDs for your image and metadata uploads</li><li>Mint the path to the meta data file (A common misconception is that you mint the image file path)</li></ul><h3>What is Minting?</h3><p>“Minting basically refers to the <strong>process of turning digital art into a part of the Ethereum blockchain</strong> as a public ledger. … NFTs ensure representation for your digital artwork. At the same time, it also ensures that the artwork can be flexibly traded or purchased in the market.”</p><p>You must mint your NFTs in order to be able to sell them / transfer ownership .</p><p>For more information on minting see <a href="https://101blockchains.com/nft-minting/"><strong>[HERE]</strong></a>.</p><h3>The Metadata file 📝</h3><p>As mentioned above Minting is pretty much a 3 step process</p><p>1- You upload your image to IPFS</p><p>2- You create and upload a metadata JSON file to IPFS</p><p>3- You pin the CID that is returned for each of these</p><p>I stated that your meta data file will contain 3 keys but it can actually be as many as you like, however you must have the 3 required keys.</p><p>Here is a real world valid example of a metadata file that i have minted to an NFT contract on the Polygon Mainnet blockchain.</p><pre>{<br>  &quot;name&quot;:&quot;Stupid Schaefer&quot;,<br>  &quot;description&quot;:&quot;number 1 of the series 1 low collection&quot;,       &quot;image&quot;:&quot;https://ipfs.infura.io/ipfs/QmPAMRJhbEKSjf6dwM65wqWmw5Jtmwi4jCS5Y78TUZ7YPW&quot;,<br>  &quot;uid&quot;:&quot;0-4-5-29-25-29-59-59-64-86-194-48&quot;,<br>  &quot;timestamp&quot;:1629664820425<br>}</pre><p>As you can see above i have name, description and image, however i also have uid and timestamp.</p><p>Its important to understand the function of the 3 required keywords so here is a break down.</p><p>1- <strong>Name</strong>: This is the name that will be displayed for your unique token on places such as <a href="https://opensea.io/"><strong>[Opensea]</strong></a></p><p>2- <strong>Description</strong>: This is the description that will be displayed for your unique token on places such as <a href="https://opensea.io/"><strong>[Opensea]</strong></a></p><p>3- <strong>Image</strong>: The image will allow your tokens image to be displayed in a users wallet and on places such as <a href="https://opensea.io/"><strong>[Opensea]</strong></a></p><p>Any further keys added can be used for your own purpose, there is no limit to amount of keys you can add.</p><h3>Free Video [Code Walkthrough]</h3><p>I have recorded a video walking through the boilerplate code <a href="https://www.youtube.com/watch?v=F0xD1DK3pe4&amp;ab_channel=G">[LINK]</a>. I really hope this helps other developers out who are looking to go into Blockchain development.</p><h3>Crypto Ghoulz</h3><p>For research into this topic i created my own blockchain based website on the polygon network, which allows users to purchase NFTs, check it out and if your feeling spicy purchase one of my NFTs. <a href="https://cryptoghoulz.com/">https://cryptoghoulz.com</a> .</p><p>If you have any questions surrounding Crypto Ghoulz get in touch via twitter.</p><h3>Project Code</h3><p>If you want to get started on this you can find a boiler plate repo <a href="https://github.com/gary-george/nft-react-boilerplate"><strong>[HERE]</strong></a>.</p><p>This is a good to go project that can help you get a real feel for how everything works.</p><h3>Links</h3><p><strong>Video Guide:</strong> <a href="https://youtu.be/F0xD1DK3pe4">https://youtu.be/F0xD1DK3pe4</a></p><p><strong>Boilerplate:</strong> <a href="https://github.com/gary-george/nft-react-boilerplate">https://github.com/gary-george/nft-react-boilerplate</a></p><p><strong>Crypto Ghoulz:</strong> <a href="https://cryptoghoulz.com/">https://cryptoghoulz.com/</a></p><p><strong>Blog Posts:</strong></p><p><strong>Part 1 of 3: </strong><a href="https://medium.com/coinmonks/guide-to-creating-your-own-nft-with-javascript-solidity-part-1-of-3-7909b80fae94">https://medium.com/coinmonks/guide-to-creating-your-own-nft-with-javascript-solidity-part-1-of-3-7909b80fae94</a></p><p><strong>Part 2 of 3: </strong><a href="https://medium.com/coinmonks/guide-to-creating-your-own-nft-with-javascript-solidity-part-2-of-3-ceaa1cb2412a">https://medium.com/coinmonks/guide-to-creating-your-own-nft-with-javascript-solidity-part-2-of-3-ceaa1cb2412a</a></p><p><strong>Part 3 of 3: </strong><a href="https://medium.com/coinmonks/guide-to-creating-your-own-nft-with-javascript-solidity-part-3-of-3-6dae8da7e3f">https://medium.com/coinmonks/guide-to-creating-your-own-nft-with-javascript-solidity-part-3-of-3-6dae8da7e3f</a></p><h3>Whats next?</h3><p>In part 3 we will be minting our NFT, purchasing it and verifying the ownership. Click <a href="https://medium.com/coinmonks/guide-to-creating-your-own-nft-with-javascript-solidity-part-3-of-3-6dae8da7e3f"><strong>[HERE]</strong></a> to view part 3.</p><blockquote>Join <a href="https://t.me/coincodecap">Coinmonks Telegram Channel</a> and learn about crypto trading and investing.</blockquote><p><strong>Also, Read</strong></p><ul><li><a href="https://medium.com/coinmonks/youhodler-vs-coinloan-vs-hodlnaut-b1050acde55a">YouHodler vs CoinLoan vs Hodlnaut</a> | <a href="https://blog.coincodecap.com/cryptohopper-vs-haasbot">Cryptohopper vs HaasBot</a></li><li><a href="https://blog.coincodecap.com/binance-vs-kraken">Binance vs Kraken</a> | <a href="https://blog.coincodecap.com/pionex-dca-bot">Dollar-Cost Averaging Trading Bot</a></li><li><a href="https://medium.com/coinmonks/buy-bitcoin-in-india-feb50ddfef94">How to buy Bitcoin in India?</a> | <a href="https://medium.com/coinmonks/wazirx-review-5c811b074f5b">WazirX Review</a> | <a href="https://blog.coincodecap.com/bitmex-review">BitMEX Review</a></li><li><a href="https://blog.coincodecap.com/bitcoin-taproot">Bitcoin Taproot</a> | <a href="https://blog.coincodecap.com/bitso-review">Bitso Review</a> | <a href="https://medium.com/coinmonks/bitcoin-credit-card-bc8ab6f377c6">Top 6 Bitcoin Credit Card</a></li><li><a href="https://blog.coincodecap.com/gemini-vs-coinbase">Gemini vs Coinbase</a> | <a href="https://blog.coincodecap.com/kraken-vs-coinbase">Coinbase vs Kraken</a> | <a href="https://blog.coincodecap.com/coinspot-vs-coinjar">CoinJar vs CoinSpot</a></li><li><a href="https://medium.com/coinmonks/bitcoin-exchange-in-india-7f1fe79715c9">Indian crypto exchange</a>| <a href="https://medium.com/coinmonks/bitcoin-savings-account-e65b13f92451">Bitcoin Savings Account</a> | <a href="https://medium.com/coinmonks/paxful-review-4daf2354ab70">Paxful Review</a></li><li><a href="https://medium.com/coinmonks/leveraged-token-3f5257808b22">Leveraged Token</a> | <a href="https://medium.com/coinmonks/crypto-exchange-dd2f9d6f3769">Best Crypto Exchange</a> | <a href="https://medium.com/coinmonks/ascendex-review-53e829cf75fa">AscendEX Review</a></li><li><a href="https://medium.com/coinmonks/godex-io-review-7366086519fb">Godex.io Review</a> | <a href="https://medium.com/coinmonks/invity-review-70f3030c0502">Invity Review</a> | <a href="https://blog.coincodecap.com/bitforex-review">BitForex Review</a> | <a href="https://medium.com/coinmonks/hitbtc-review-c5143c5d53c2">HitBTC Review</a></li><li><a href="https://medium.com/coinmonks/binance-fees-8588ec17965">Binance Fees</a> | <a href="https://medium.com/coinmonks/botcrypto-review-2021-build-your-own-trading-bot-coincodecap-6b8332d736c7">Botcrypto Review</a> | <a href="https://blog.coincodecap.com/crypto-com-alternatives">Crypto.com Alternatives</a></li><li><a href="https://blog.coincodecap.com/trading-signal">What are the Trading Signals?</a> | <a href="https://blog.coincodecap.com/bitstamp-coinbase">Bitstamp vs Coinbase</a></li><li><a href="https://blog.coincodecap.com/profitfarmers-review">ProfitFarmers Review</a> | <a href="https://blog.coincodecap.com/cornix-trading-bot">How to use Cornix Trading Bot</a></li><li><a href="https://medium.com/coinmonks/mxc-exchange-review-3af0ec1cba8c">MXC Exchange Review</a> | <a href="https://blog.coincodecap.com/pionex-vs-binance">Pionex vs Binance</a> | <a href="https://blog.coincodecap.com/pionex-arbitrage-bot">Pionex Arbitrage Bot</a></li><li><a href="https://medium.com/coinmonks/my-experience-with-crypto-copy-trading-d6feb2ce3ac5">My Experience with Crypto Copy Trading</a> | <a href="https://medium.com/coinmonks/coinbase-review-6ef4e0f56064">Coinbase Review</a></li><li><a href="https://blog.coincodecap.com/coinflex-review">CoinFLEX Review</a> | <a href="https://blog.coincodecap.com/aex-exchange-review">AEX Exchange Review</a> | <a href="https://blog.coincodecap.com/upbit-review">UPbit Review</a></li><li><a href="https://blog.coincodecap.com/ascendex-margin-trading">AscendEx Margin Trading</a> | <a href="https://blog.coincodecap.com/bitfinex-staking">Bitfinex Staking</a> | <a href="https://blog.coincodecap.com/bitflyer-review">bitFlyer Review</a></li><li><a href="https://blog.coincodecap.com/sparrow-exchange-review">Sparrow Exchange Review</a> | <a href="https://blog.coincodecap.com/nash-exchange-review">Nash Exchange Review</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ceaa1cb2412a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/guide-to-creating-your-own-nft-with-javascript-solidity-part-2-of-3-ceaa1cb2412a">Guide to creating your own NFT with Javascript &amp; Solidity – UPDATED to include video guide –…</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Guide to creating your own NFT with Javascript & Solidity  (Part 1 of 3)]]></title>
            <link>https://medium.com/coinmonks/guide-to-creating-your-own-nft-with-javascript-solidity-part-1-of-3-7909b80fae94?source=rss-4a42073343ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/7909b80fae94</guid>
            <category><![CDATA[nft]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[nft-collectibles]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Gary George]]></dc:creator>
            <pubDate>Mon, 06 Sep 2021 21:52:04 GMT</pubDate>
            <atom:updated>2023-01-06T17:59:43.209Z</atom:updated>
            <content:encoded><![CDATA[<h3>Guide to creating your own NFT with Javascript &amp; Solidity — UPDATED to include video guide – 🚀 (Part 1 of 3)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GW1a9AE8iDRkB1i44NrHFg.png" /></figure><h3>What is an NFT ?</h3><p>NFT stands for non-fungible token. Non-fungible is an economic term that you could use to describe things like your furniture, a song file, or your computer. These things are not interchangeable for other items because they have unique properties.</p><p>The NFT world is relatively new. In theory, the scope for NFTs is anything that is unique that needs provable ownership.</p><p>For a deeper explanation check this [<a href="https://ethereum.org/en/nft/"><strong>LINK</strong></a>]</p><h3>What is A Crypto Wallet ?</h3><p>A blockchain/crypto wallet is a digital wallet that allows users to store and manage their Bitcoin, Ether, and other cryptocurrencies.</p><p>When creating a website that allows users to interact with NFTs , you will need to connect your wallet to the website.</p><p>The most popular wallet used is [<a href="https://metamask.io/"><strong>Meta Mask</strong></a>], this can be used as a browser extension for Chrome and Firefox.</p><p>See [<a href="https://www.coinbase.com/learn/crypto-basics/what-is-a-crypto-wallet"><strong>HERE</strong></a>] for a more in depth explanation of blockchain wallets.</p><h3>How do you create an NFT ?</h3><p>There are many ways to create an NFT without needing any development experience, A great example of this is [<a href="https://opensea.io/"><strong>Opensea</strong></a>].</p><p>You can create an Opensea account link it to your crypto wallet (MetaMask) and create NFTs simply by interacting with the website as you would any other web app.</p><p>While this is a good option , we wont be doing this in our example, we are going to go deep in the rabbit hole of becoming a blockchain developer 🚀.</p><p>We will need to do a few things in order to create our NFTs:</p><ul><li>Write a smart contract in [<a href="https://docs.soliditylang.org/en/v0.8.7/introduction-to-smart-contracts.html"><strong>Solidity</strong></a>] (this is the language used on the blockchain)</li><li>Deploy your contract to your chosen network</li><li>Create your NFT asset</li><li>Create your corresponding metadata file for your NFT</li><li>Mint your metadata file to the blockchain using your contract</li></ul><h3>Writing your own NFT contract</h3><p>The great thing with smart contracts is that there are lots of boiler plates that you can leverage off. The biggest provider of these is [<a href="https://openzeppelin.com/"><strong>Open Zeppelin</strong></a>] .</p><p>“OpenZeppelin Contracts help you minimize risk by using battle-tested libraries of smart contracts for Ethereum and other blockchains. It includes the most used implementations of ERC standards.”</p><p>This is great for us as developers as we can get our contracts created with much ease.</p><p>An NFT contract aka a <a href="https://eips.ethereum.org/EIPS/eip-721"><strong>[ERC721 Contract]</strong></a><strong> </strong>allows us to create/mint and purchase/transfer ownership of digital assets/NFTs.</p><p>Here is a complete solidity example for a real world NFT contract:</p><pre><em>// SPDX-License-Identifier: MIT</em></pre><pre>pragma solidity &gt;=0.6.0 &lt;0.8.0;</pre><pre>import &quot;@openzeppelin/contracts/token/ERC721/ERC721.sol&quot;;</pre><pre>import &quot;@openzeppelin/contracts/access/Ownable.sol&quot;;</pre><pre> contract NFT <em>is</em> ERC721, Ownable {</pre><pre>    address payable public _owner;</pre><pre>    mapping(uint256 =&gt; bool) public sold;</pre><pre>    mapping(uint256 =&gt; uint256) public price;</pre><pre>    event Purchase(address owner, uint256 price, uint256 id, string uri);</pre><pre>    constructor() ERC721(&quot;YOUR TOKEN&quot;, &quot;TOKEN&quot;) {</pre><pre>     _owner = msg.sender;</pre><pre>    }</pre><pre>function mint(string memory _tokenURI, uint256 _price)</pre><pre> public</pre><pre> onlyOwner</pre><pre> returns (bool)</pre><pre> {</pre><pre>    uint256 _tokenId = totalSupply() + 1;</pre><pre>    price[_tokenId] = _price;</pre><pre>    _mint(address(this), _tokenId);</pre><pre>    _setTokenURI(_tokenId, _tokenURI);</pre><pre>    return true;</pre><pre> }</pre><pre>function buy(uint256 _id) external payable {</pre><pre>    _validate(_id);<em> </em></pre><pre>    _trade(_id);</pre><pre>    emit Purchase(msg.sender, price[_id], _id, tokenURI(_id));</pre><pre> }</pre><pre> function _validate(uint256 _id) internal {</pre><pre>    require(_exists(_id), &quot;Error, wrong Token id&quot;);</pre><pre>    require(!sold[_id], &quot;Error, Token is sold&quot;);</pre><pre>    require(msg.value &gt;= price[_id], &quot;Error, Token costs more&quot;); </pre><pre>  }</pre><pre>  function _trade(uint256 _id) internal {</pre><pre>    _transfer(address(this), msg.sender, _id);</pre><pre>    _owner.transfer(msg.value);</pre><pre>    sold[_id] = true;</pre><pre>  }</pre><pre>}</pre><p>The above example extends 2 existing openzeppelin contracts to enable you to fulfil the entire required spec in place for <a href="https://eips.ethereum.org/EIPS/eip-721"><strong>[ERC721]</strong></a>.</p><p>The main thing to take note of is the two strings passed into the constructor the first “YOUR TOKEN” would be the parent name for all of your tokens created with the contract, the second argument “TOKEN” is the short code that will be used for your Tokens.</p><h3>Deploying your first NFT Contract</h3><p>Once you have written your contract you will need to deploy it to test it out, One big thing to note about the block chain is that all contracts are immutable , this means that a bug will forever live in your contract , you can not make changes to a contract once it is deployed 😢.</p><p>Thankfully we have test environments available to us ,There are multiple test nets available. My preferred test net to use is Rinkeby, Here is some further reading on <a href="https://docs.ethhub.io/using-ethereum/test-networks/"><strong>[Test Nets]</strong></a><strong>.</strong></p><p>A massive benefit of the test nets is that you can reset your contracts and overwrite mistakes. Which means you can test out your contracts until you are happy and then deploy to the main net (where it is immutable)</p><p>To get your contracts on the test net you will want to use <a href="https://www.trufflesuite.com/"><strong>[Truffle]</strong></a>, Truffle is an excellent tool which allows you to easily deploy.</p><p>Im not going to go through truffle deployment but <a href="https://www.youtube.com/watch?v=CgXQC4dbGUE&amp;t=78s&amp;ab_channel=DappUniversity"><strong>[THIS VIDEO]</strong></a> will give you all the information you need.</p><h3>Free Video [Code Walkthrough]</h3><p>I have recorded a video walking through the boilerplate code <a href="https://www.youtube.com/watch?v=F0xD1DK3pe4&amp;ab_channel=G">[LINK]</a>. I really hope this helps other developers out who are looking to go into Blockchain development.</p><h3>Crypto Ghoulz</h3><p>For research into this topic i created my own blockchain based website on the polygon network, which allows users to purchase NFTs, check it out and if your feeling spicy purchase one of my NFTs. <a href="https://cryptoghoulz.com/">https://cryptoghoulz.com</a> .</p><p>If you have any questions surrounding <a href="https://cryptoghoulz.com/"><strong>[Crypto Ghoulz]</strong></a> get in touch via <a href="https://twitter.com/Crypto_Ghoulz"><strong>[Twitter]</strong></a>.</p><h3><strong>Project Code</strong></h3><p>If you want to get started on this you can find a boiler plate repo <a href="https://github.com/gary-george/nft-react-boilerplate"><strong>[HERE]</strong></a>.</p><p>This is a good to go project that can help you get a real feel for how everything works.</p><h3>Links</h3><p><strong>Video Guide:</strong> <a href="https://youtu.be/F0xD1DK3pe4">https://youtu.be/F0xD1DK3pe4</a></p><p><strong>Boilerplate:</strong> <a href="https://github.com/gary-george/nft-react-boilerplate">https://github.com/gary-george/nft-react-boilerplate</a></p><p><strong>Crypto Ghoulz:</strong> <a href="https://cryptoghoulz.com/">https://cryptoghoulz.com/</a></p><p><strong>Blog Posts:</strong></p><p><strong>Part 1 of 3: </strong><a href="https://medium.com/coinmonks/guide-to-creating-your-own-nft-with-javascript-solidity-part-1-of-3-7909b80fae94">https://medium.com/coinmonks/guide-to-creating-your-own-nft-with-javascript-solidity-part-1-of-3-7909b80fae94</a></p><p><strong>Part 2 of 3: </strong><a href="https://medium.com/coinmonks/guide-to-creating-your-own-nft-with-javascript-solidity-part-2-of-3-ceaa1cb2412a">https://medium.com/coinmonks/guide-to-creating-your-own-nft-with-javascript-solidity-part-2-of-3-ceaa1cb2412a</a></p><p><strong>Part 3 of 3: </strong><a href="https://medium.com/coinmonks/guide-to-creating-your-own-nft-with-javascript-solidity-part-3-of-3-6dae8da7e3f">https://medium.com/coinmonks/guide-to-creating-your-own-nft-with-javascript-solidity-part-3-of-3-6dae8da7e3f</a></p><h3>Whats next?</h3><p>In part 2 We will be interacting with our new NFT contract and discussing how to upload your assets ready for minting.</p><p>Click <a href="https://garygeorge84.medium.com/guide-to-creating-your-own-nft-with-javascript-solidity-part-2-of-3-ceaa1cb2412a"><strong>[HERE]</strong></a> for part 2.</p><blockquote>Join <a href="https://t.me/coincodecap">Coinmonks Telegram Channel</a> and learn about crypto trading and investing.</blockquote><p><strong>Also, Read</strong></p><ul><li><a href="https://medium.com/coinmonks/youhodler-vs-coinloan-vs-hodlnaut-b1050acde55a">YouHodler vs CoinLoan vs Hodlnaut</a> | <a href="https://blog.coincodecap.com/cryptohopper-vs-haasbot">Cryptohopper vs HaasBot</a></li><li><a href="https://blog.coincodecap.com/binance-vs-kraken">Binance vs Kraken</a> | <a href="https://blog.coincodecap.com/pionex-dca-bot">Dollar-Cost Averaging Trading Bot</a></li><li><a href="https://medium.com/coinmonks/buy-bitcoin-in-india-feb50ddfef94">How to buy Bitcoin in India?</a> | <a href="https://medium.com/coinmonks/wazirx-review-5c811b074f5b">WazirX Review</a> | <a href="https://blog.coincodecap.com/bitmex-review">BitMEX Review</a></li><li><a href="https://blog.coincodecap.com/bitcoin-taproot">Bitcoin Taproot</a> | <a href="https://blog.coincodecap.com/bitso-review">Bitso Review</a> | <a href="https://medium.com/coinmonks/bitcoin-credit-card-bc8ab6f377c6">Top 6 Bitcoin Credit Card</a></li><li><a href="https://blog.coincodecap.com/gemini-vs-coinbase">Gemini vs Coinbase</a> | <a href="https://blog.coincodecap.com/kraken-vs-coinbase">Coinbase vs Kraken</a> | <a href="https://blog.coincodecap.com/coinspot-vs-coinjar">CoinJar vs CoinSpot</a></li><li><a href="https://medium.com/coinmonks/bitcoin-exchange-in-india-7f1fe79715c9">Indian crypto exchange</a>| <a href="https://medium.com/coinmonks/bitcoin-savings-account-e65b13f92451">Bitcoin Savings Account</a> | <a href="https://medium.com/coinmonks/paxful-review-4daf2354ab70">Paxful Review</a></li><li><a href="https://medium.com/coinmonks/leveraged-token-3f5257808b22">Leveraged Token</a> | <a href="https://medium.com/coinmonks/crypto-exchange-dd2f9d6f3769">Best Crypto Exchange</a> | <a href="https://medium.com/coinmonks/ascendex-review-53e829cf75fa">AscendEX Review</a></li><li><a href="https://medium.com/coinmonks/godex-io-review-7366086519fb">Godex.io Review</a> | <a href="https://medium.com/coinmonks/invity-review-70f3030c0502">Invity Review</a> | <a href="https://blog.coincodecap.com/bitforex-review">BitForex Review</a> | <a href="https://medium.com/coinmonks/hitbtc-review-c5143c5d53c2">HitBTC Review</a></li><li><a href="https://medium.com/coinmonks/binance-fees-8588ec17965">Binance Fees</a> | <a href="https://medium.com/coinmonks/botcrypto-review-2021-build-your-own-trading-bot-coincodecap-6b8332d736c7">Botcrypto Review</a> | <a href="https://blog.coincodecap.com/crypto-com-alternatives">Crypto.com Alternatives</a></li><li><a href="https://blog.coincodecap.com/trading-signal">What are the Trading Signals?</a> | <a href="https://blog.coincodecap.com/bitstamp-coinbase">Bitstamp vs Coinbase</a></li><li><a href="https://blog.coincodecap.com/profitfarmers-review">ProfitFarmers Review</a> | <a href="https://blog.coincodecap.com/cornix-trading-bot">How to use Cornix Trading Bot</a></li><li><a href="https://medium.com/coinmonks/mxc-exchange-review-3af0ec1cba8c">MXC Exchange Review</a> | <a href="https://blog.coincodecap.com/pionex-vs-binance">Pionex vs Binance</a> | <a href="https://blog.coincodecap.com/pionex-arbitrage-bot">Pionex Arbitrage Bot</a></li><li><a href="https://medium.com/coinmonks/my-experience-with-crypto-copy-trading-d6feb2ce3ac5">My Experience with Crypto Copy Trading</a> | <a href="https://medium.com/coinmonks/coinbase-review-6ef4e0f56064">Coinbase Review</a></li><li><a href="https://blog.coincodecap.com/coinflex-review">CoinFLEX Review</a> | <a href="https://blog.coincodecap.com/aex-exchange-review">AEX Exchange Review</a> | <a href="https://blog.coincodecap.com/upbit-review">UPbit Review</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7909b80fae94" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/guide-to-creating-your-own-nft-with-javascript-solidity-part-1-of-3-7909b80fae94">Guide to creating your own NFT with Javascript &amp; Solidity 🚀 (Part 1 of 3)</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GraphQL facade for REST API with AWS Lambda]]></title>
            <link>https://garygeorge84.medium.com/graphql-facade-for-rest-api-with-aws-lambda-88a00ca082c1?source=rss-4a42073343ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/88a00ca082c1</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Gary George]]></dc:creator>
            <pubDate>Thu, 10 Dec 2020 14:37:22 GMT</pubDate>
            <atom:updated>2020-12-10T14:37:22.415Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*RHWi_Erl7eAzfsiDf3sanQ.png" /></figure><h3>What exactly are we doing here?</h3><p>We are going to create a <strong><em>GraphQL schema,</em></strong> This will wrap calls to an existing <strong>REST API</strong>. This schema will receive and resolve <strong>GraphQL</strong> queries all on the client-side.</p><p>The main benefit of this is, instead of having multiple endpoints for accessing your data you can focus on one and let the query determine what is returned.</p><p>Our GraphQL schema will act as a <strong>facade</strong> layer, Facade is just a fancy way of saying ‘it is simplifying our existing <strong>REST API’</strong>.</p><p>I have prepared a boilerplate repo for reference <a href="https://github.com/gary-george/graphql-lambda">Here</a>.</p><h3><strong>What is a REST API?</strong></h3><p>A RESTful <strong>API</strong> is an architectural style for an application program interface (<strong>API</strong>) that uses HTTP requests to access and use data. That data can be <strong>used</strong> to GET, PUT, POST, and DELETE data types, which refers to the reading, updating, creating, and deleting operations concerning resources.</p><p><em>Check </em><a href="https://searchapparchitecture.techtarget.com/definition/RESTful-API"><em>here</em></a><em> for a great explanation.</em></p><h3><strong>What is GraphQL?</strong></h3><p>GraphQL is a query language for your API, and a server-side runtime for executing queries by using a type system you define for your data. GraphQL isn’t tied to any specific database or storage engine and is instead backed by your existing code and data.</p><p><em>Check </em><a href="https://graphql.org/learn/"><em>here</em></a><em> for a great explanation.</em></p><h3>Setting up the serverless project</h3><p>The <a href="https://github.com/gary-george/graphql-lambda">boilerplate</a> for this project was created using <a href="https://www.serverless.com/">Serverless</a>.<br>For a guide on how to get set up look <a href="https://www.serverless.com/framework/docs/providers/aws/guide/quick-start/">here</a>.</p><p>If you would just like to get a <strong>GraphQL</strong> instance set up locally you can ignore the serverless step and start the project using <strong><em>node server</em></strong><em>, </em>this will start everything up using Node, Express &amp; GraphQL.</p><h3>Our existing REST API</h3><p>To not pollute this post with unnecessary complications we will be using a static JSON file to mock out our REST API response.</p><p>Anytime a call would be made to an endpoint in a <strong>resolver</strong> we will simply return the relevant JSON response.</p><h3><strong>Resolvers, Schema &amp; Types</strong></h3><p>For queries and mutations in GraphQL you need to implement Resolvers, Schema &amp; Types, here is a brief breakdown of each.</p><p><a href="https://www.tutorialspoint.com/graphql/">Here</a> is a great resource for GraphQL information.</p><p><strong>Resolvers:</strong></p><blockquote>A resolver is a collection of functions that generate a response for a GraphQL query. In simple terms, a resolver acts as a GraphQL query handler.</blockquote><p><strong>Schema:</strong></p><blockquote>A GraphQL schema is at the core of any GraphQL server implementation. It describes the functionality available to the client applications that connect to it.</blockquote><p><strong>Types:</strong></p><blockquote>GraphQL is a strongly typed language. Type System defines various data types that can be used in a GraphQL application. The type system helps to define the schema, which is a contract between client and server.</blockquote><h3>What is a GraphQL Query?</h3><p>A GraphQL operation can either be a read or a write operation. A GraphQL query is used to read or fetch values while a mutation is used to write or post values. In either case, the operation is a simple string that a GraphQL server can parse and respond to with data in a specific format. The popular response format that is usually used for mobile and web applications is JSON.</p><h3>What is a GraphQL Mutation?</h3><p>Mutation queries modify data in the data store and return a value. It can be used to insert, update, or delete data. Mutations are defined as a part of the schema.</p><h3>What is GrapiQL?</h3><p><strong>GraphiQL</strong> is the <strong>GraphQL</strong> integrated development environment (<a href="https://www.redhat.com/en/topics/middleware/what-is-ide#:~:text=An%20integrated%20development%20environment%20(IDE,graphical%20user%20interface%20(GUI).">IDE</a>), it allows us to run all of our queries and mutations and test everything is working as expected.</p><p>To access <strong>GraphiQL</strong> for this project you simply need to go to the root /.</p><p>Once there you will see the interface, The left-hand side is for inputting your query/mutation, The right-hand side is where the results/errors will display.</p><p>In the readme of the <a href="https://github.com/gary-george/graphql-lambda">boilerplate</a>, I have given you example queries to use in GraphiQL.</p><p><strong>Query example:</strong></p><pre>{</pre><pre> posts{</pre><pre>  _id,</pre><pre>  title,</pre><pre>  subtitle</pre><pre> }</pre><pre>}</pre><p><strong>Mutation Example:</strong></p><pre>mutation {</pre><pre> addPost(</pre><pre>    title: &quot;Brand New Post&quot;,</pre><pre>    subtitle: &quot;This is super interesting&quot;,</pre><pre>    text: &quot;The body for the new blog post&quot;</pre><pre> ) {</pre><pre>    title</pre><pre>    subtitle</pre><pre>    text</pre><pre> }</pre><pre>}</pre><h3>Putting it all together</h3><p>We will make a project that can be run locally on a <strong>Node server</strong> or from an <strong>AWS Lamda </strong>instance. 🚀</p><p><em>Before you begin to follow along make sure you have Node installed.</em></p><p>I created a boilerplate repo to accompany this post <a href="https://github.com/gary-george/graphql-lambda">Here</a>.</p><p>To run the boilerplate simply follow these 3 steps:</p><ul><li>clone the repo</li><li>install dependencies (yarn or npm install)</li><li>run: node server</li></ul><p>Once it is up and running head to the URL and you will be presented with GraphiQL.</p><p>Here is a bit of an explanation of the main pieces of this project.</p><h3><strong>Node setup:</strong></h3><p>To get our Node instance running we only need two files:</p><p><strong>server.js</strong></p><p>See <a href="https://github.com/gary-george/graphql-lambda/blob/main/server.js">here</a>, This file is a basic file for starting our Node application.</p><p><strong>app.js</strong></p><p>See <a href="https://github.com/gary-george/graphql-lambda/blob/main/src/app.js">here</a>, This sets up our express server and our GraphQL endpoint.</p><p>Interesting to note in the below block, <strong><em>graphiql: true</em></strong><em> </em>Allows us to use the <strong>GraphiQL </strong>tool mentioned above.</p><pre>app.use( ‘/’, graphqlHTTP({ <br>    graphiql: true, <br>    schema: GraphQLSchema<br>}));</pre><h3><strong>Lambda setup:</strong></h3><p>If you are only interested in getting this running in Node you can skip this.</p><p>However, if you would like to get this running on AWS then you will need to create a <strong>serverless.yml </strong>file and the corresponding handler function.</p><p><strong>Serverless.yml</strong></p><p>See <a href="https://github.com/gary-george/graphql-lambda/blob/main/serverless.yml">here</a>, This file sets up everything you need with AWS API Gateway, enabling the endpoints for using GraphiQL in AWS.</p><p>This is the block that handles the creation of the routes, The great part about this is it saves you having to log in and manually create the routes.</p><pre>functions:  <br>    getPosts:    <br>        handler: lambda.handler    <br>        events: <br>          - http:          <br>               path: posts          <br>               method: get          <br>               cors: true      <br>          - http:          <br>               path: posts          <br>               method: post          <br>               cors: true</pre><p><strong>lambda.js</strong></p><p>See <a href="https://github.com/gary-george/graphql-lambda/blob/main/lambda.js">here</a>, The handler function will be triggered when our API Gateway routes are invoked.</p><p>We are using the npm package ‘<a href="https://www.npmjs.com/package/aws-serverless-express">aws-serverless-express</a>’, This allows us to Run serverless applications and REST APIs using our existing <a href="https://nodejs.org/">Node.js</a> application framework, on top of <a href="https://aws.amazon.com/lambda/">AWS Lambda</a> and <a href="https://aws.amazon.com/api-gateway/">Amazon API Gateway</a>.</p><h3><strong>GraphQL setup:</strong></h3><p>Everything you need for the GraphQL schema set up can be found in this <a href="https://github.com/gary-george/graphql-lambda/tree/main/src/graphql">directory</a>.</p><p>We have our queries, resolvers, types, and mutations separated into separate directories.</p><p><strong>schema.js</strong></p><p>See <a href="https://github.com/gary-george/graphql-lambda/blob/main/src/graphql/schema.js">here</a>, Our schema js file is the heart of our GraphQL setup, here we specify our queries and mutations that we have configured.</p><p>Our <strong>Query</strong> (see <a href="https://github.com/gary-george/graphql-lambda/blob/main/src/graphql/queries/Posts.js">here</a>) is linked to our resolver (see <a href="https://github.com/gary-george/graphql-lambda/blob/main/src/graphql/resolvers/Posts.js">here</a>), This is where you would make your API call to retrieve data, in this example, I am returning a static JSON object to simulate data coming back from an API.</p><p>You will notice in our <strong>Query</strong> that we reference our <strong>type</strong> (see <a href="https://github.com/gary-george/graphql-lambda/blob/main/src/graphql/types/Posts.js">here</a>), This assures that the data we are returned is exactly what we expect, allowing GraphQL to work its magic and work as expected.</p><p>Our <strong>Mutation</strong> (see <a href="https://github.com/gary-george/graphql-lambda/blob/main/src/graphql/mutations/Posts.js">here</a>) Lists out the payload it expects to receive along with the types of data expected. If a sufficient payload is passed it will make it into the resolve function.</p><p>The resolve function is where you would fire off the payload to your API for insertion or update, then return the mutated response. For this example, we will just be returned the args that we sent.</p><h3>Wrapping up:</h3><p>I hope this helped to demystify how to implement GraphQL.</p><p>As mentioned above clone the <a href="https://github.com/gary-george/graphql-lambda">boilerplate</a> and get started.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88a00ca082c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Jenkins API with Node]]></title>
            <link>https://garygeorge84.medium.com/jenkins-api-with-node-4d3826322367?source=rss-4a42073343ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d3826322367</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[continuous-integration]]></category>
            <category><![CDATA[jenkins]]></category>
            <dc:creator><![CDATA[Gary George]]></dc:creator>
            <pubDate>Fri, 08 May 2020 10:59:17 GMT</pubDate>
            <atom:updated>2020-05-08T11:01:15.275Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bdEeG-mJRqGxLqY92TDPAA.png" /></figure><p>This is a continuation of my previous post [<a href="https://medium.com/@garygeorge84/jenkins-inside-docker-on-ubuntu-with-bitbucket-integration-for-node-4f8d21ab226b">Here</a>]. 🚀</p><p>In the previous post, I went through the process of setting up Jenkins and integrating with your bit bucket account. This time around I’m going to show you how to use the Jenkins API, I will also show you how to interact with this from your Node Application. 🔥</p><h3>Jenkins API</h3><p>You can get to your Jenkins API by navigating to :</p><p><strong>[JENKINS_DOMAIN]:[PORT]/api/</strong></p><p>From here you will be able to see the available types of the API (JSON, XML, or Python). I will be using the JSON API.</p><p>You will need to create an API Token to interact with the Jenkins API, to do that you need to navigate to :</p><p><strong>[JENKINS_DOMAIN]:[PORT]/me/configure</strong></p><p>Further information can be found [<a href="https://wiki.jenkins.io/display/JENKINS/Remote+access+API">HERE</a>].</p><h3>CURL Requests</h3><p>The simplest way to talk to your Jenkins API is via the command line and using <a href="https://en.wikipedia.org/wiki/CURL">Curl</a>.</p><p>Don’t worry too much if you have never heard of <a href="https://en.wikipedia.org/wiki/CURL">Curl</a>, I will provide a couple of examples in <a href="https://nodejs.org/en/about/">Node</a> below.</p><p>The starting syntax for all of these requests is:</p><pre>[USER_NAME]:[JENKINS_TOKEN] [JENKINS_DOMAIN]:[PORT]/api/json?pretty=true</pre><h3>Here is a list of requests you can make using Curl</h3><p>To make any of the requests below, simply replace the [KEYS] in brackets with your information and paste it into the terminal. You will be presented back with the relevant data for the given request.</p><p><strong>Authenticate a user</strong></p><pre>curl -u [USER_NAME]:[JENKINS_TOKEN] [JENKINS_DOMAIN]:[PORT]/api/json?pretty=true</pre><p><strong>Build status</strong></p><pre>curl -g -u [USER_NAME]:[JENKINS_TOKEN] [JENKINS_DOMAIN]:[PORT]/api/json?pretty=true&amp;tree=jobs[name,color]</pre><p><strong>Specific job config</strong></p><pre>curl -g -u [USER_NAME]:[TOKEN] [JENKINS_DOMAIN]:[PORT]/job/[JOB_NAME]/job/master/config.xml -o config.xml</pre><p><strong>Getting last build data</strong></p><pre>curl -g -u [USER_NAME]:[TOKEN] [JENKINS_DOMAIN]:[PORT]/job/[JOB_NAME]/job/master/lastBuild/api/json</pre><h3>Using Node 🚀</h3><p>I will be using <a href="https://www.npmjs.com/package/request-promise-native">request-promise-native</a> to call the Jenkins API.</p><p>Here are a couple of examples of accessing the Jenkins API using Node.</p><p>You can add these routes into your existing Node project, You will need to swap out the Variables with your own information:</p><pre>JENKINS_BASE_URL = [JENKINS_DOMAIN]:[PORT]</pre><pre>JENKINS_JOB = The name given to the jenkins job you wish to get information from </pre><pre>JENKINS_USER_NAME = The user name from the Jenkins credential you created earlier</pre><pre>JENKINS_API_KEY = The Token from the Jenkins credential you created earlier</pre><p><strong>Get Recent Builds</strong></p><p>This will bring back information for the latest 5 builds of a specific Jenkins job.</p><pre>app.get(&#39;/v1/jenkins-recent-bulids&#39;, <strong>async</strong> (req, res) =&gt; {</pre><pre><strong>const</strong> { builds } = <strong>await</strong> request({</pre><pre>uri: `${JENKINS_BASE_URL}/job/${JENKINS_JOB}/job/master/api/json?tree=builds[number,url,result,timestamp]{0,5}`,</pre><pre>auth: {</pre><pre>user: JENKINS_USER_NAME,</pre><pre>pass: JENKINS_API_KEY,</pre><pre>},</pre><pre>json: <strong>true</strong>,</pre><pre>});</pre><pre>res.json({</pre><pre>builds,</pre><pre>});</pre><pre>});</pre><p><strong>Getting the Latest Build</strong></p><p>This will go off and retrieve the latest build information for a specific Jenkins job.</p><pre>app.get(&#39;/v1/jenkins-get-last-build&#39;, async (req, res) =&gt; {</pre><pre>const { result, url, timestamp } = await request({</pre><pre>uri: `${JENKINS_BASE_URL}/job/${JENKINS_JOB}/job/master/lastBuild/api/json`,</pre><pre>auth: {</pre><pre>user: JENKINS_USER_NAME,</pre><pre>pass: JENKINS_API_KEY,</pre><pre>},</pre><pre>json: true,</pre><pre>});</pre><pre>res.json({</pre><pre>success: result.toLowerCase() === &#39;success&#39;,</pre><pre>url,</pre><pre>time: moment(timestamp).format(&#39;MMM Do YYYY&#39;),</pre><pre>});</pre><pre>});</pre><p>I am limiting what I am getting from the returned data to ‘result, URL, and timestamp’ using ES6 <a href="https://hacks.mozilla.org/2015/05/es6-in-depth-destructuring/">Destructuring</a>.</p><pre><strong>Success</strong> : Whether the job passed or failed<br><strong>Url </strong>: The url to the build in Jenkins<br><strong>Timestamp </strong>: the timestamp for when the job</pre><p>you can get everything by changing:</p><pre>const { result, url, timestamp } = await request ...</pre><p>to</p><pre>const data = await request ...</pre><h3><strong>Summary</strong></h3><p>The <strong>Jenkins API</strong> can be really helpful if you are planning on creating some sort of admin center for a customer, allowing them visibility of how everything is going, Or even creating your own dashboard which allows you to monitor your builds without having to log into <strong>Jenkins</strong> to check. 👍</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d3826322367" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Jenkins inside Docker on Ubuntu with BitBucket integration for Node]]></title>
            <link>https://garygeorge84.medium.com/jenkins-inside-docker-on-ubuntu-with-bitbucket-integration-for-node-4f8d21ab226b?source=rss-4a42073343ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f8d21ab226b</guid>
            <category><![CDATA[jenkins]]></category>
            <category><![CDATA[bitbucket]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[node]]></category>
            <dc:creator><![CDATA[Gary George]]></dc:creator>
            <pubDate>Thu, 30 Apr 2020 18:34:26 GMT</pubDate>
            <atom:updated>2020-04-30T18:39:35.368Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H9psuHUxmjPy2eSivILQPA.png" /></figure><p>In this, I will go over step by step how to set up <strong>Jenkins</strong> inside <strong>Docker</strong> on <strong>Ubuntu</strong> with <strong>BitBucket</strong> integration for <strong>Node</strong>.</p><p>If you have a VPS running <strong>Ubuntu</strong>, you may have wanted to set up your own <strong>Jenkins</strong> instance from scratch and integrate it into your <strong>Bitbucket</strong> repositories.</p><p>This was a task I put off for a long time for a number of reasons, One being I thought it would be too complicated, another reason was I didn&#39;t feel that I had the need to do this for my personal projects.</p><p>Once I decided to give it a go I found that it&#39;s not actually that bad to get set up.</p><p><em>Here is a boilerplate project for reference [</em><a href="https://github.com/gary-george/jenkins-docker-boilerplate"><em>Link to repo🔥</em></a><em>].</em></p><h3>Get started</h3><p>First of all clone the boilerplate repo [<a href="https://github.com/gary-george/jenkins-docker-boilerplate">Here</a>], It is super simple with only a Makefile. See [<a href="https://opensource.com/article/18/8/what-how-makefile">Here</a>] for information on what a Makefile is.</p><h3>Commands in the Makefile</h3><ul><li>make build (fresh build of the container)</li><li>make run (initial run of the container)</li><li>make start (starts the container if it falls over)</li><li>make stop (stop the container)</li><li>make clean (stop and remove the container)</li></ul><h3>Building the container</h3><p>Using the repo is easy, you can get started super quick by running the below commands from the terminal:</p><ul><li>make build</li><li>make run</li></ul><p>The above two commands will pull down the Jenkins docker image and get it running on port 8888.</p><p>Once the container is running you will need to get the initial admin password to get started with setting up Jenkins.</p><p>To do this you need to check the logs for the container, you can do this by running:</p><ul><li>docker ps -a</li></ul><p>Make a note of the container id provided in the output</p><p>Once you have the id you can then run:</p><ul><li>docker logs — tail 2500 [CONTAINER_ID]</li></ul><p>This will show you all of the logs for your new container. Inside the logs, you will find the Jenkins admin password.</p><p>Navigate to <a href="http://[YOUR_DOMAIN]:8888/">http://[YOUR_DOMAIN]:8888/</a> and start the Jenkins install wizard. Enter the admin password and complete installation.</p><h3>Permission errors on Ubuntu</h3><p>You may find that when you try to do <strong>make build</strong>, you are returned a permissions error.</p><p>You will need to allow the ssh user (this must be in your <a href="https://linuxize.com/post/how-to-add-user-to-sudoers-in-ubuntu/">sudoers</a> list) to grant sudo permissions to docker. You can do this by:</p><ul><li>SSH into your VPS with your user</li></ul><p>run:</p><ul><li>sudo usermod -aG docker $USER</li><li>sudo reboot</li></ul><p>Once this is complete you will be able to retry building the Jenkins docker image using:</p><ul><li>make build</li><li>make run</li></ul><h3>Hooking up to Bitbucket</h3><p>Once the <strong>Jenkins</strong> wizard is all complete and you are logged in, You will need to install the [<a href="https://plugins.jenkins.io/build-pipeline-plugin/"><strong>build pipeline</strong></a><strong>]</strong> plugin.</p><p>Once that is installed you will need to generate an <a href="https://www.ssh.com/ssh/public-key-authentication">SSH Keypair</a> on your VPS.</p><ul><li>ssh into the server and run <strong>ssh-keygen</strong></li><li>copy the private key and then paste into your Jenkins credential ( to get the key you can use: cat /var/www/vhosts/[YOUR_DOMAIN]/.ssh/id_rsa )</li><li>copy the public key and then paste into bitbucket repo (to get the key you can use: cat /var/www/vhosts/[YOUR_DOMAIN]/.ssh/id_rsa.pub )</li></ul><p>Once that is done you will need to create a Jenkins Pipeline job.</p><p>In the Jenkins pipeline config, you need to select the credential you just created for your user.</p><p><strong>Next, we need to allow Jenkins to run the pipeline.</strong></p><ul><li>Inside Jenkins we must add the <strong>node plugin</strong> in global tools, select a version of node and set the name like this: <strong>node-10.17.0</strong></li><li>in your applications <strong>Jenkinsfile</strong> you will need to reference the name you gave above like this: <strong>tools {nodejs “node-10.17.0”}</strong></li></ul><p><strong>Jenkinsfile?</strong></p><p>In your application that you wish to connect to Jenkins, you will need to create a [<a href="https://www.jenkins.io/doc/book/pipeline/jenkinsfile/"><strong>Jenkinsfile</strong></a>] in the route directory (same level as package.json).</p><p>Here is an example of a valid Jenkinsfile:</p><p>You can see below that you can set <strong>environment variables</strong> and <strong>multiple steps</strong> for the build. Each step can run tasks specified in your package.json</p><pre>pipeline {<br>  agent any<br>  tools {<br>    nodejs “node-10.17.0”<br>  }<br>  environment{<br>    NODE_ENV = ‘production’<br>    APP_PORT = 3000<br>  }<br>  stages {<br>    stage (‘Install’) {<br>      steps {<br>        sh ‘HOME=`pwd` npm install’<br>      }<br>    }<br>    stage (‘Lint’) {<br>      steps {<br>        sh “npm run lint”<br>      }<br>    }<br>    stage (‘Unit test’) {<br>      steps {<br>        sh “npm run test:unit”<br>      }<br>    }<br>  }<br>  post {<br>    always {<br>      echo ‘This will always run’<br>    }<br>    success {<br>      echo ‘This will run only if successful’<br>    }<br>    failure {<br>      echo ‘This will run only if failed’<br>    }<br>    unstable {<br>      echo ‘This will run only if the run was marked as unstable’<br>    }<br>    changed {<br>      echo ‘This will run only if the state of the Pipeline has changed’<br>      echo ‘For example, if the Pipeline was previously failing but is now successful’<br>    }<br>  }</pre><pre>}</pre><h3>Triggering a build after a commit in your repo</h3><p>This is referred to as a Jenkins webhook.</p><p>You will need to set up some config in Jenkins and in Bitbucket:</p><p><strong>In Jenkins:</strong></p><ul><li>install the ‘bitbucket’ plugin</li><li>create a Jenkins freestyle project</li><li>under Source Code Management &gt; connect to bitbucket git repo</li><li>under Build Triggers &gt; select Build when a change is pushed to BitBucket</li><li>under Build &gt; select the pipeline job that you wish to be triggered</li></ul><p><strong>In Bit Bucket:</strong></p><ul><li>go to your repo select &gt; settings &gt; webhooks</li><li>give your new webhook a title and then give a URL of : <a href="http://georgewebdesign.co.uk:8080/bitbucket-hook/">[DOMAIN_WHERE_YOUR_JENKINS_IS_RUNNING]:8888/bitbucket-hook/</a></li><li>select &gt; trigger on repository push</li></ul><h3>Summary</h3><p>Now when you push a commit into your repo your Jenkins job will be triggered and your <strong>Jenkinsfile</strong> will be used to run the various steps you have specified such as unit tests, linting, component tests, etc.</p><p>I will create a separate post explaining how to use Node to talk to your Jenkins instance and get build information via the Jenkins API.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f8d21ab226b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build your own JWT Authentication server with Node]]></title>
            <link>https://garygeorge84.medium.com/jwt-authentication-server-with-node-from-scratch-88ca2d22aebc?source=rss-4a42073343ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/88ca2d22aebc</guid>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[jwt]]></category>
            <dc:creator><![CDATA[Gary George]]></dc:creator>
            <pubDate>Mon, 27 Apr 2020 18:38:23 GMT</pubDate>
            <atom:updated>2020-04-28T18:24:33.487Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*9pWUdYPAwCQoWdEnvZli4A.jpeg" /></figure><p>I am going to go over how to create a JWT authentication server 🎉.</p><p><em>Here is a boilerplate project for reference [</em><a href="https://github.com/gary-george/jwt-boilerplate"><em>Link to repo🔥</em></a><em>].</em></p><h3>What is JWT</h3><p>JSON Web Token (JWT) is an open standard (<a href="https://tools.ietf.org/html/rfc7519">RFC 7519</a>) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret (with the <strong>HMAC</strong> algorithm) or a public/private key pair using <strong>RSA</strong> or <strong>ECDSA</strong>.</p><p>— information taken from [<a href="https://jwt.io/">Here</a>].</p><h3>Why use JWT</h3><p>Here are some scenarios where JSON Web Tokens are useful:</p><ul><li><strong>Authorization</strong>: This is the most common scenario for using JWT. Once the user is logged in, each subsequent request will include the JWT, allowing the user to access routes, services, and resources that are permitted with that token. Single Sign-On is a feature that widely uses JWT nowadays, because of its small overhead and its ability to be easily used across different domains.</li><li><strong>Information Exchange</strong>: JSON Web Tokens are a good way of securely transmitting information between parties. Because JWTs can be signed — for example, using public/private key pairs — you can be sure the senders are who they say they are. Additionally, as the signature is calculated using the header and the payload, you can also verify that the content hasn’t been tampered with.</li></ul><p>— information taken from [<a href="https://jwt.io/">Here</a>].</p><h3>Tokens</h3><p>JWT requires you to use two tokens in the flow for your user.</p><p><strong>1- Access Token:</strong></p><p>An access token allows you to verify your user and grant them access to resources. Access tokens should generally have a TTL (time to live) after this time they expire and are no longer valid.</p><p><strong>2- Refresh Token:</strong></p><p>Your refresh token comes into play when your access token expires. The refresh token allows you to generate a new valid access token. This will allow your users to continue using your website without having to log back in. Refresh tokens will also have a TTL but will generally be longer than access tokens.</p><p>Refresh tokens should be stored in a database and expire after a period of time (for instance an hour) after this time the user will need to log back into the app to start the process of generating tokens again.</p><p>It is important to expire refresh tokens to help keep your user’s data secure.</p><h3>Getting Started</h3><p>The first thing you need to do is knock up a quick node server. For reference, you can clone the boilerplate repo [<a href="https://github.com/gary-george/jwt-boilerplate">Here</a>].</p><p>You will need to implement MongoDB (other databases are [<a href="https://www.tutorialsteacher.com/nodejs/data-access-in-nodejs">available</a>]).</p><p>We need to create 2 collections ;</p><p>One to store our <strong>created users</strong> and another for our<strong> refresh tokens</strong></p><h3>Mongoose Schemas</h3><p>Once your Node server is up and running you are going to want to set up a couple of Mongoose schemas. See boilerplate [<a href="https://github.com/gary-george/jwt-boilerplate/tree/master/server/db">Here</a>] for reference.</p><p><strong>- For storing your user’s account information.</strong></p><pre>{<br>email: { type: mongoose.SchemaTypes.Email, required: true, index: true },<br>username: { type: String, required: true, index: true },<br>password: { type: String, required: true },<br>created_at: { type: Date },<br>updated_at: { type: Date }},<br>{timestamps: { createdAt: &#39;created_at&#39;, updatedAt: &#39;updated_at&#39; }}</pre><p><strong>- For storing valid refresh tokens.</strong></p><p>One thing to note in the refresh token schema is the ‘expires’: ‘60m’. This ensures the document is deleted after 60 minutes.</p><pre>{<br>userIdentifier: { type: String, required: true, index: true },<br>refreshToken: { type: String, required: true, index: true },<br>created_at: { type: Date },<br>updated_at: { type: Date },<br>expire_at: {type: Date,default: Date.now,index: { expires: &#39;60m&#39; }<br>}},<br>{timestamps: { createdAt: &#39;created_at&#39;, updatedAt: &#39;updated_at&#39; }<br>}</pre><h3>Application Flow</h3><p>Here is a quick overview of how a user will interact with your server if you adopt JWT authentication:</p><ul><li>User is created</li><li>User logs in</li><li>User is granted an <strong>access token</strong> and a <strong>refresh token</strong></li><li>the <strong>access token</strong> allows them to access data from endpoints by verifying the <strong>access token</strong> is valid. In the boilerplate, we accomplish this by using middleware which we have named <strong>authenticateToken</strong> (you can find this on the /v1/posts endpoint ).</li><li>When the <strong>access token</strong> expires (10 minutes in the boilerplate) we send our <strong>refresh token</strong> to the <strong>/v1/refresh</strong> endpoint and we are returned a new <strong>access token</strong></li><li>After 60 minutes (based on our schema set up) the<strong> refresh token</strong> expires from the database, this forces the user to log in once again to be granted a new <strong>access token</strong> and a <strong>refresh token</strong></li><li>If the logout route is called, the refresh token is deleted from the collection and the user will need to log in again to generate a new one.</li></ul><p>The times used in the boilerplate can be adapted to suit your needs.</p><p>you are able to use the free tool [<a href="https://jwt.io/">Here</a>] to paste in an access token and decode it to see what is inside it.</p><p>If you are storing anything precious in your access tokens then I would suggest encrypting the data.</p><h3>Server Routes</h3><p>There are a number of routes you will need to create in your application. For reference see [<a href="https://github.com/gary-george/jwt-boilerplate/blob/master/server/routes/jwt.js">Here</a>] in the boilerplate.</p><p>It is also worth a mention that in the boilerplate, I am using <a href="https://www.npmjs.com/package/@hapi/joi">Joi</a> for validation on routes that accept a payload. This allows us to fail fast if we are sent an invalid payload.</p><p>Here is an overview of the routes in the boilerplate application.</p><h3>/v1/create-user</h3><p><strong>headers to set:</strong></p><p>authorization: API_KEY</p><p><strong>body to send:</strong></p><p>{<br> “email”:”<a href="/service/mailto:garytest@test.com">garygeorge@test.com</a>”,<br> “username”: “boilerplate”,<br> “pass”:”thePassword”<br>}</p><p><strong>The result to expect:</strong></p><p>{<br> “msg”: “user successfully created”<br>}</p><h3>/v1/login</h3><p><strong>headers to set: N/A</strong></p><p><strong>body to send:</strong></p><p>{<br> “username”: “boilerplate”,<br> “pass”:”thePassword”<br>}</p><p><strong>The result to expect:</strong></p><p>{<br> “accessToken”: “eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1ZWE2ZDNlNWQwNmNmNzcxYmQ1Njk4MGMiLCJlbWFpbCI6Imdhcnl0ZXN0QHRlc3QuY29tIiwidXNlcm5hbWUiOiJib2lsZXJwbGF0ZSIsImlhdCI6MTU4ODAwODk3MiwiZXhwIjoxNTg4MDA5NTcyfQ.LnXy-a5BqHK_5QGqGR85c2tYlGG2tR-Kc-BCb9m1S60”,<br> “refreshToken”: “eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1ZWE2ZDNlNWQwNmNmNzcxYmQ1Njk4MGMiLCJlbWFpbCI6Imdhcnl0ZXN0QHRlc3QuY29tIiwidXNlcm5hbWUiOiJib2lsZXJwbGF0ZSIsImlhdCI6MTU4ODAwODk3Mn0.7_IDk1vR1kfPPsKRE85uZP2p_2RqphRwJ503SDQNmk4”,<br> “user”: {<br> “_id”: “5ea6d3e5d06cf771bd56980c”,<br> “email”: “<a href="/service/mailto:garytest@test.com">garytest@test.com</a>”,<br> “username”: “boilerplate”<br> }<br>}</p><h3>/v1/get-user</h3><p><strong>headers to set:</strong></p><p>authorization: API_KEY</p><p><strong>body to send:</strong></p><p>{<br> “username”: “boilerplate”<br>}</p><p><strong>The result to expect:</strong></p><p>{<br> “_id”: “5ea6d3e5d06cf771bd56980c”,<br> “email”: “<a href="/service/mailto:garytest@test.com">garygeorge@test.com</a>”,<br> “username”: “boilerplate”,<br> “password”: “03364c7b9d47a5fce08279d496fb292875a0fc1730826c23955ca0e8986c436756bfd433969bb88ac4008c44cd83d5368064eff9fa0ee539665f44632ba2020f90b7e5d3c4480508b1cb77940e0916e33fc2db6565f30d597e08afc4076e864fe798e180c607bb6582b36b”,<br> “created_at”: “2020–04–27T12:45:25.449Z”,<br> “updated_at”: “2020–04–27T12:45:25.449Z”,<br> “__v”: 0<br>}</p><h3>/v1/delete-user</h3><p><strong>headers to set:</strong></p><p>authorization: API_KEY</p><p><strong>body to send:</strong></p><p>{<br> “username”: “boilerplate”<br>}</p><p><strong>The result to expect:</strong></p><p>{<br> “msg”: “User boilerplate has been deleted”<br>}</p><h3>/v1/verify-token</h3><p><strong>headers to set:</strong></p><p>authorization: Bearer [VALID_ACCESS_TOKEN]</p><p><strong>body to send: N/A</strong></p><p><strong>The result to expect:</strong></p><p>{<br> “user”: {<br> “_id”: “5ea6d3e5d06cf771bd56980c”,<br> “email”: “<a href="/service/mailto:garytest@test.com">garygeorge@test.com</a>”,<br> “username”: “boilerplate”,<br> “iat”: 1588009363,<br> “exp”: 1588009963<br> }<br>}</p><h3>/v1/refresh-token</h3><p><strong>headers to set: N/A</strong></p><p><strong>body to send:</strong></p><p>{<br> “refreshToken”: “VALID_REFRESH_TOKEN”<br>}</p><p><strong>The result to expect:</strong></p><p>{<br> “accessToken”: “eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE1ODc5OTE1NjUsImV4cCI6MTU4Nzk5MjE2NX0.637pVzyUGM7hSi2BzbqQY8IgBunePL_Jwy24DZDzCSg”<br>}</p><h3>/v1/posts</h3><p><strong>headers to set:</strong></p><p>authorization: Bearer [VALID_ACCESS_TOKEN]</p><p><strong>body to send: N/A</strong></p><p><strong>The result to expect:</strong></p><p>[{</p><p>username: ‘exampleUser’,</p><p>title: ‘post 1’,</p><p>}]</p><h3>/v1/logout</h3><p><strong>headers to set:</strong></p><p>authorization: API_KEY</p><p><strong>body to send:</strong></p><p>“refreshToken”: “VALID_REFRESH_TOKEN”<br>}</p><p><strong>The result to expect: N/A</strong></p><h3>Running the project</h3><p>To run the project successfully you will need to have MongoDB installed globally and have it running. 🏃</p><p>To start Mongo up locally you can open a new terminal tab and type <strong>mongod</strong></p><p>This will start up Mongo and allow your project to connect and create the required collections.</p><p>Create a .env file and populate it with</p><pre>API_KEY=a6cf3b77b02ad165f731060b549f0aa8d</pre><pre>ENCRYPTION_KEY=f0678TGYUTR767309mZ!y749F765456</pre><pre>ACCESS_TOKEN_SECRET=8a94cbd836053aa6cf028dd35c718f4186e1a06a40d49c5043d56e97d37eca38f17bdfa5ebfb3f190d2d133be5e13e8151b705fd9602ff4dc03f7b166296f668</pre><pre>REFRESH_TOKEN_SECRET=4d7b389f595b8c1309324ad1e53066135477be016802236201e062a8d4a13fa51a6095b42066b70bb14bb10812fb5b25ed98a9ea4353c43f8e7597f9bbc679d8</pre><p>To run the node server you will need to run:</p><p><strong>yarn</strong> (to install dependencies)</p><p><strong>yarn start </strong>(to start the server)</p><p>Once the server is up and running you will be able to access the end points (listed above) on port 5000.</p><p>When testing locally running applications, My personal preference is to use <a href="https://insomnia.rest/"><strong>Insomnia</strong></a> but <a href="https://www.postman.com/"><strong>Postman</strong></a> is also an excellent rest-client application. 💻</p><p>A rest-client allows you to send data to your locally running endpoints and get the response an actual user would. 🚀</p><p>I hope this was helpful and allows you to get started with JWT Authentication. 👍</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88ca2d22aebc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>