WebAssembly

WebAssembly

WebAssembly is a new type of code that can be run in modern web browsers — it is a low-level assembly-like language with a compact binary format that runs with near-native performance and provides languages such as C/C++ and Rust with a compilation target so that they can run on the web.

Webapi: Go Lang Web Assembly Bindings for DOM, HTML Etc

WebAPI

Go Language Web Assembly bindings for DOM, HTML etc

WARNING: The current API is in very early state and should be consider to be expremental. There is upcommig changed like moving types into multiple packages.

This library is trying to be feature complete and up to date with current standard to let everything a browser having to offect be available in WebAssembly in a Go API accessable. To achive this most of the code is generated from WebIDL files. WebIDL files can be found in different standard making it easiser to be up to date than handwritten binding code.

Example:

func main() {
    element := webapiall.GetWindow().Document().GetElementById("foo")
    // NOTE: After Go 1.12, the extra call to JSValue() will no loger   be needed
    button := webapiall.HTMLButtonElementFromJS(element.JSValue())
    button.SetValue("Hello World")
}

Roadmap

MilestoneStatusDescription
1OngoingBe abto to read and and understand all of WebIDL syntax. Notible missing thing are namespace and union
2PlannedEasy up the syntax. Promise will be refactor and other places where simplifications can be done. Classes can be renamed like clipboard.ClipboardPermission to clipboard.Permission.
3PlannedAPI Stability with a predefined release schedule. Documentation and added examples

More infomation of missing stuff can be found on the generator status info.

Author: Gowebapi
Source Code: https://github.com/gowebapi/webapi 
License: BSD-3-Clause license

#go #golang #web #api #webassembly 

Webapi: Go Lang Web Assembly Bindings for DOM, HTML Etc

Vert: WebAssembly interop Between Go and JS Values

vert 

Package vert provides WebAssembly interop between Go and JS values.

Install

GOOS=js GOARCH=wasm go get github.com/norunners/vert

Examples

Hello World!

Below is a trivial string value interop.

package main

import "github.com/norunners/vert"

func main() {
    v := vert.ValueOf("Hello World!")
    // Use v as a JS value.

    s := ""
    v.AssignTo(&s)
    // Use s as a Go value.
}

Structs & Objects

Go structs and JS objects interop seamlessly.

package main

import "github.com/norunners/vert"

type Data struct {
    Message string
}

func main() {
    v := vert.ValueOf(Data{
        Message: "Hello World!",
    })
    // e.g. {"Message": "Hello World!"}

    d := &Data{}
    v.AssignTo(d)
}

Tagged Struct Fields

Tagged struct fields allow defined JS field names.

package main

import "github.com/norunners/vert"

type Data struct {
    Message string `js:"msg"`
}

func main() {
    v := vert.ValueOf(Data{
        Message: "Hello World!",
    })
    // The defined JS tag names the field.
    // e.g. {"msg": "Hello World!"}

    d := &Data{}
    v.AssignTo(d)
}

Error Handling

AssignTo returns an error value.

package main

import "github.com/norunners/vert"

type Data struct {
    Message string
}

func main() {
    v := vert.ValueOf("Hello World!")

    d := &Data{}
    if err := v.AssignTo(d); err != nil {
        // Handle error.
    }
}

Why?

Package syscall/js, of the Go standard library, has limited interop support between Go and JS values.

  1. The function js.ValueOf will not accept struct types. The result panics with ValueOf: invalid value.
  2. The type js.Value. does not support an Interface or assignment method for non-basic Go values. However, the methods Bool, Int, Float and String support basic Go values.

Package vert leverages and extends syscall/js to accommodate these shortcomings.

Author: Norunners
Source Code: https://github.com/norunners/vert 
License: MIT license

#go #golang #webassembly 

Vert: WebAssembly interop Between Go and JS Values

Tinygo: Go Compiler for Small Places. Microcontrollers, WebAssembly

TinyGo - Go compiler for small places 

TinyGo is a Go compiler intended for use in small places such as microcontrollers, WebAssembly (Wasm), and command-line tools.

It reuses libraries used by the Go language tools alongside LLVM to provide an alternative way to compile programs written in the Go programming language.

Here is an example program that blinks the built-in LED when run directly on any supported board with onboard LED:

package main

import (
    "machine"
    "time"
)

func main() {
    led := machine.LED
    led.Configure(machine.PinConfig{Mode: machine.PinOutput})
    for {
        led.Low()
        time.Sleep(time.Millisecond * 1000)

        led.High()
        time.Sleep(time.Millisecond * 1000)
    }
}

The above program can be compiled and run without modification on an Arduino Uno, an Adafruit ItsyBitsy M0, or any of the supported boards that have a built-in LED, just by setting the correct TinyGo compiler target. For example, this compiles and flashes an Arduino Uno:

tinygo flash -target arduino examples/blinky1

Installation

See the getting started instructions for information on how to install TinyGo, as well as how to run the TinyGo compiler using our Docker container.

Supported boards/targets

You can compile TinyGo programs for microcontrollers, WebAssembly and Linux.

The following 85 microcontroller boards are currently supported:

For more information, see this list of boards. Pull requests for additional support are welcome!

Currently supported features:

For a description of currently supported Go language features, please see https://tinygo.org/lang-support/.

Documentation

Documentation is located on our web site at https://tinygo.org/.

You can find the web site code at https://github.com/tinygo-org/tinygo-site.

Getting help

If you're looking for a more interactive way to discuss TinyGo usage or development, we have a #TinyGo channel on the Gophers Slack.

If you need an invitation for the Gophers Slack, you can generate one here which should arrive fairly quickly (under 1 min): https://invite.slack.golangbridge.org

Contributing

Your contributions are welcome!

Please take a look at our Contributing page on our web site for details.

Project Scope

Goals:

  • Have very small binary sizes. Don't pay for what you don't use.
  • Support for most common microcontroller boards.
  • Be usable on the web using WebAssembly.
  • Good CGo support, with no more overhead than a regular function call.
  • Support most standard library packages and compile most Go code without modification.

Non-goals:

  • Be efficient while using zillions of goroutines. However, good goroutine support is certainly a goal.
  • Be as fast as gc. However, LLVM will probably be better at optimizing certain things so TinyGo might actually turn out to be faster for number crunching.
  • Be able to compile every Go program out there.

Why this project exists

We never expected Go to be an embedded language and so its got serious problems...

-- Rob Pike, GopherCon 2014 Opening Keynote

TinyGo is a project to bring Go to microcontrollers and small systems with a single processor core. It is similar to emgo but a major difference is that we want to keep the Go memory model (which implies garbage collection of some sort). Another difference is that TinyGo uses LLVM internally instead of emitting C, which hopefully leads to smaller and more efficient code and certainly leads to more flexibility.

The original reasoning was: if Python can run on microcontrollers, then certainly Go should be able to run on even lower level micros.

Author: Tinygo-org
Source Code: https://github.com/tinygo-org/tinygo 
License: View license

#go #golang #webassembly 

Tinygo: Go Compiler for Small Places. Microcontrollers, WebAssembly

Go-canvas: Library to Use HTML5 Canvas From Go-WASM

go-canvas

go-canvas is a pure go+webassembly Library for efficiently drawing on a html5 canvas element within the browser from go without requiring calls back to JS to utilise canvas drawing functions.

The library provides the following features:

  • Abstracts away the initial DOM interactions to setup the canvas.
  • Creates the shadow image frame, and graphical Context to draw on it.
  • Initializes basic font cache for text using truetype font.
  • Sets up and handles requestAnimationFrame callback from the browser.

Concept

go-canvas takes an alternate approach to the current common methods for using canvas, allowing all drawing primitives to be done totally with go code, without calling JS.

standard syscall way

In a standard WASM application for canvas, the go code must create a function that responds to requestAnimationFrame callbacks and renders the frame within that call. It interacts with the canvas drawing primitives via the syscall/js functions and context switches. i.e.

laserCtx.Call("beginPath")
laserCtx.Call("arc", gs.laserX, gs.laserY, gs.laserSize, 0, math.Pi*2, false)
laserCtx.Call("fill")
laserCtx.Call("closePath")

Downsides of this approach (for me at least), are messy JS calls which can't easily be checked at compile time, forcing a full redraw every frame, even if nothing changed on that canvas, or changes being much slower than the requested frame rate.

go native way

go-canvas allows all drawing to be done natively using Go by creating an entirely separate image buffer which is drawn to using a 2D drawing library. I'm currently using one from https://github.com/llgcode/draw2d which provides most of the standard canvas primitives and more. This shadow Image buffer can be updated at whatever rate the developer deems appropriate, which may very well be slower than the browsers animation rate.

This shadow Image buffer is then copied over to the browser canvas buffer during each requestAnimationFrame callback, at whatever rate the browser requests. The handling of the callback and copy is done automatically within the library.

Secondly, this also allows the option of drawing to the image buffer, outside of the requestAnimationFrame callback if required. After some testing it appears that it is still best to do the drawing within the requestAnimationFrame callback.

go-canvas provides several options to control all this, and take care of the browser/dom interactions

  • User specifies the go render/draw callback method when calling the START function. This callback passes the graphical context to the render routine.
  • Render routine can choose to return whether any drawing took place. If it returns false, then the requestAnimationFrame callback does nothing, just returns immediately, saving CPU cycles. (No point to copy buffers and redraw if nothing has changed) This allows the drawing to be adaptive to the rate of data changes.
  • The 'start' function accepts a maxFPS parameter. The library will automatically throttle the requestAnimationFrame callback to only do redraws or image buffer copies to this max rate. Note it MAY be slower depending on the Render time, and the requirements of the browser doing other work. When a tab is hidden, the browser regularly reduces and may even stop call to the animation callback. No critical timing should be done in the render/draw routings.
  • You may pass 'nil' for the render function. In this case all drawing happens totally under the users control, outside of the library. This may be more useful in future when WASM supports proper threading. Right now however, testing shows it is slower as all work is in the one thread, and you lose the scheduling benefits of the requestAnimationFrame call.

Drawing therefore, is pure go. i.e.

func Render(gc *draw2dimg.GraphicContext) bool {
    // {some movement code removed for clarity, see the demo code for full function}
    // draws red 🔴 laser
    gc.SetFillColor(color.RGBA{0xff, 0x00, 0x00, 0xff})
    gc.SetStrokeColor(color.RGBA{0xff, 0x00, 0x00, 0xff})

    gc.BeginPath()
    gc.ArcTo(gs.laserX, gs.laserY, gs.laserSize, gs.laserSize, 0, math.Pi*2)
    gc.FillStroke()
    gc.Close()
return true  // Yes, we drew something, copy it over to the browser

If you do want to render outside the animation loop, a simple way to cause the code to draw the frame on schedule, independent from the browsers callbacks, is to use time.Tick. An example is in the demo app below.

If however your image is only updated from user input or some network activity, then it would be straightforward to fire the redraw only when required from these inputs. This can be controlled within the Render function, by just returning FALSE at the start. Nothing is draw, nor copied (saving CPU time) and the previous frames data remains.

Known issues !

There is currently a likely race condition for long draw functions, where the requestAnimationFrame may get a partially completed image buffer. This is more likely the longer the user render operation takes. Currently think how best to handle this, ideally without locks. Turns out this is not an issue, due to the single threaded nature. Eventually if drawing is in a separate thread, this will have to be handled.

Demo

A simple demo can be found in: ./demo directory. This is a shameless rewrite of the 'Moving red Laser' demo by Martin Olsansky https://medium.freecodecamp.org/webassembly-with-golang-is-fun-b243c0e34f02

Compile with GOOS=js GOARCH=wasm go build -o main.wasm

Includes a Caddy configuration file to support WASM, so will serve by just running 'caddy' in the demo directory and opening browser to http://localhost:8080

Live

Live Demo available at: https://markfarnan.github.io/go-canvas

Future

This library was written after a weekend of investigation and posted on request for the folks on #webassembly on Gophers Slack.

I intend to extend it further, time permitting, into fully fledged support package for all things go-canvas-wasm related, using this image frame method.

Several of the ideas I'm considering are:

  •  Support for layered canvas, at least 3 for 'background', 'action' and 'user interaction'
  •  Traps & helper functions for mouse interactions over the canvas
  •  Unit tests - soon as I figure out how to do tests for WASM work.
  •  Performance improvements in the image buffer copy - https://github.com/agnivade/shimmer/blob/c073303a81ab9a90b6fc14eb6d90c3a1b930025e/load_image_cb.go#L40 has been suggested as a place to start.
  •  Detect if nothing has changed for the frame, and if so, don't even recopy the buffer, saving yet more time. May be useful for layers that change less frequently.
  •  Multiple draw / render frames to fix the 'incomplete image' problem. -- Not actually a problem
  •  Tidy up the close/end frame functionality to properly release resources on page unload and prevent 'browser reload errors' due to missing animation callback function.
  •  Update for Go 1.13 and Go Modules
  •  Add FPS Calculator metric

Others ? Feedback, suggestions etc. welcome. I can be found on Gophers Slack, #Webassembly channel.

Mark Farnan, February 2020

Author: Markfarnan
Source Code: https://github.com/markfarnan/go-canvas 
License: Apache-2.0 license

#go #golang #canvas #html5 #wasm 

Go-canvas: Library to Use HTML5 Canvas From Go-WASM

Dom: DOM Library for Go and WASM

Go DOM binding (and more) for WebAssembly

This library provides a Go API for different Web APIs for WebAssembly target.

It's in an active development, but an API will be carefully versioned to avoid breaking users. Use Go dependency management tools to lock a specific version.

More information about Go's WebAssembly support can be found on Go's WebAssembly wiki page.

Features:

  • Better JS API (wrappers for syscall/js)
  • Basic DOM manipulation, styles, events
  • Input elements
  • SVG elements and transforms
  • LocalStorage and SessionStorage
  • Extension APIs (tested on Chrome):
    • Native Messaging
    • Bookmarks
    • Tabs
  • net-like library for WebSockets
    • Tested with gRPC
  • wasm-server for fast prototyping

Quickstart

Pull the library and install wasm-server (optional):

go get -u github.com/dennwc/dom
go install github.com/dennwc/dom/cmd/wasm-server

Run an example app:

cd $GOPATH/src/github.com/dennwc/dom
wasm-server

Check result: http://localhost:8080/

The source code is recompiled on each page refresh, so feel free to experiment!

Similar Projects

Editor Configuration

If you are using Visual Studio Code, you can use workspace settings to configure the environment variables for the go tools.

Your settings.json file should look something like this:

{
    "go.toolsEnvVars": { "GOARCH": "wasm", "GOOS": "js" }
}

Author: Dennwc
Source Code: https://github.com/dennwc/dom 
License: Apache-2.0 license

#go #golang #dom #webassembly 

Dom: DOM Library for Go and WASM

How to Create A AssemblyScript NEAR Contract By Hand

Simple Counter

This example shows how to make a simple NEAR AssemblyScript contract. Normally the sdk does a lot behind the scenes. When calling a function with arguments it deserializes it for you, so in this example each exposed function has no arguments. Furthermore, if a function returns a value the sdk will serialize it for you too, so again these functions do not return anything.

Unfortunately current the serialization must be imported, which adds bloat to the generated binary. In this example we only use the host imports and the generated optimized binary is only 309 bytes!

The advantage to using AssemblyScript is that you can write code that generates Wasm text that is readable and close to the code that you wrote. This makes AssemblyScript a great language to learn about WebAssembly!

Notes

Running yarn build will build both a debug and a release version of the binary and a text version.

See build/debug/simple_counter_as.wat and build/release/simple_counter_as.wat for the generated Wasm.

Running yarn test will run a simple unit test.

Download Details:
Author: near-examples
Source Code: https://github.com/near-examples/simple_counter_as
License: View license

#near #webassembly  #blockchain  #smartcontract 

How to Create A AssemblyScript NEAR Contract By Hand

How to Generate NEAR Protocol Code_hash

Generating NEAR code_hash

This repo presents code that generates what NEAR Protocol calls code_hash, a smart contract fingerprint which can be used to verify that a specific compiled contract binary has been deployed to an account.

Background

To see the code_hash of any account on NEAR, use NEAR CLI

near state <account name>

Result for an account with no contract deployed (notice that code_hash is all 1s)

Account <account name>
{
  amount: '102900000000000000000000001',
  locked: '0',
  code_hash: '11111111111111111111111111111111',
  storage_usage: 182,
  storage_paid_at: 0,
  block_height: 19316729,
  block_hash: 'Co3DDFoyPcjJGmq8mn8GcUK2G8nsAXnHBydQQ1tCqMPB',
  formattedAmount: '102.900000000000000000000001'
}

Result for an account with a contract deployed (notice that code_hash is not all 1s)

Account <account name>
{
  amount: '2927089174323286789664185899',
  locked: '0',
  code_hash: 'F6iocDrCDzBCxUN9PKPeVp7GqDuPve4g3ypHQQrmEw5E',
  storage_usage: 185222,
  storage_paid_at: 0,
  block_height: 19316946,
  block_hash: '7ogFBMePQkKf6EtmEwdXsgVHdpFjpRpvGiH2WvsTqmtk',
  formattedAmount: '2,927.089174323286789664185899'
}

Usage

The instructions below include steps to generate the code_hash for Wasm contracts in as few steps as possible.

NOTE:

This code has been tested on 1 computer: a Macbook running macOS 10.15.7

Your results may vary ;)

Server

Run node src/server/make-code-hash greeting.wasm

Note the output in the console

Result for greeting.wasm

A8BLJRUyRmAMBakF6JVFnSx5EGn2zA6jMhEHDzinmbwf

--- done ---

You can deploy this same contract to a new NEAR TestNet account and note the code_hash is the same. In this way you can be certain that this Wasm binary is the exact match of the one that is deployed to a NEAR account

Bonus: a Python implementation is also included in the server folder. Usage of this script is cat <filename> | wasm-to-codehash

Web

  1. Open the index.html file in a web browser
  2. Open your web browser developer console since output is printed to the console in this case
  3. Drag and drop one or more files from the contracts/ folder onto the "Drop Zone" box on the web page
  4. Note the output in the browser's developer console

--- done ---

Notice that this code sample separates Wasm contract files from non-Wasm contract files as part of it's reporting output

Dependencies

This work relies entirely on the following libraries:

Download Details:
Author: near-examples
Source Code: https://github.com/near-examples/code-hash-generator
License:

#near  #blockchain  #smartcontract #webassembly #javascript 

How to Generate NEAR Protocol Code_hash
Helene  Ward

Helene Ward

1653626340

Stlite Project : Streamlit without Server

This is a quick tutorial and walkthrough of an interesting project Stlite by Yuichiro Tachibana (Tsuchiya) whitphx.

stlite project - https://github.com/whitphx/stlite
stlite demo code - https://github.com/amrrs/stlite-demo

#streamlit #python #webassembly #Stlite

Stlite Project : Streamlit without Server

WebAssembly Landscape 2022

WebAssembly Landscape 2022

The technology landscape for Wasm is growing every day. Join me for a tour of WebAssembly, where we will analyze areas of rapid growth for Wasm to predict the future of application development. Wasm is finding a home in every layer of the technical stack. When it comes to creating plugins and adding extensibility to projects, Wasm is rapidly becoming the de facto solution with excellent support for multiple languages. Another trend is serverless where we are seeing Wasm revolutionize application development via actor and event-driven architectures. Looking towards the future, it's not hard to imagine Wasm becoming the default runtime for the entire stack. Imagine applications compiled to Wasm, distributed and networked with a Wasm filter, admitted by a Wasm Open Policy Agent rule, versioned using a Wasm native package manager, Wasm clients that run on any device in the web or edge device, and the expressions used to operate on data are driven by Wasm.

#webassembly #wasm #programming 

WebAssembly Landscape 2022

What is WebAssembly? It's the Future of Web Development

WebAssembly is the Future of Web Development

Javascript has been around for over 20 years now. It's time for a change. WebAssembly was released in 2017, and is now supported by all major browsers. More and more people are starting to use it. Is a web revolution coming?


 

WebAssembly — Future of Web Development?

Google Maps is pretty cool, right? You can zoom in at any arbitrary point on the planet or peak at your neighbour’s terrace pool, which you always have been jealous of. All of these can be done right there in your browser. Have you ever wondered how it works?

Streaming an entire globe’s worth of images, data, 3D models so efficiently in your browser is a wonder by itself. How can Google achieve that when most of the websites have trouble even loading those annoying popups? Indeed, this wouldn’t be possible with plain old Javascript.

In a nutshell, the answer is WebAssembly! While most websites use Javascript, HTML, and some server-side framework to load and display data, Google Maps or Google Earth uses Web Assembly to run native binary code on the browser. Web Assembly is faster than any possible web framework or language out there, and in this article, we will dive into its know-how.

History of WebAssembly

Before we learn more about the working of WebAssembly, first let’s understand why it was created. It all started when a team of developers in Mozilla in 2015 worked to make Javascript more efficient to support heavy applications like Video Games on the web. In this process, they created WebAssembly, which was initially demonstrated to execute Unity’s Angry Bots game on the web.

So what is WebAssembly?

Let’s look at the description given on the official website of web assembly:

WebAssembly (abbreviated Wasm) is a binary instruction format for a stack-based virtual machine. Wasm is designed as a portable compilation target for programming languages, enabling deployment on the web for client and server applications.’

In simpler terms, WebAssembly is a new type of code, which is written in .wasm format and is very close to Machine language. The Wasm file is converted into a binary instruction (file written in 0s and 1s) and then compiled and rendered on the webpage. Since the WebAssembly file is very similar to C or Machine Language, it is fast in execution, which makes it a powerful tool for running heavy applications like Video Games, Video Files, 3D models, Porting Desktop Applications, etc.,

This has a massive impact on the way websites made. WebAssembly allows you to run programs written in various languages like C++, Rust, Python, Java, etc., on the web with near-native speeds. Developers are no longer restricted to the usage of the Javascript language to make web applications.

WebAssembly is statically typed, uses linear memory, and is stored in binary format. All of these features allow wasm files to be rendered on the web at near-native speed, i.e., the speed you would get if you run the program on a command line. That’s amazing, right? What’s more impressive is that now you are not restricted to the usage of only JS based libraries. The ability to support existing tools and libraries to use in the browser and the associated potential support for speedup is the main features that make WebAssembly so enthralling.

JavaScript and WebAssembly

The above diagram shows how a typical JS code is parsed and rendered on the web. JavaScript is a dynamically typed language in which variable types don’t need to be mentioned upfront or compiled ahead. It does make JS really easy to use and write, but the obvious drawback is that the JS engine has to do a lot more work to make the code work. It has to parse, compile, and optimize the code as it’s being run. On the other hand, WebAssembly is a statically typed code, which means, unlike JS, the engine doesn’t need to speculate during compilation about what types the various variables have. Most of the optimization is also done during the compilation period before it even reaches the browser. Memory is managed manually, just like in languages C/C++. All of these give much better performance and reliability.

So, the question now emerges that is WebAssembly the perfect replacement for JavaScript?

Well, the answer is ‘not exactly.’ WebAssembly was never created to replace or compete with JavaScript. It was an additional tool which was designed to improve the web platform by making it more powerful. It is intended to complement JS language and allowing developers to take advantage of multiple languages.

It is also not necessarily true that JavaScript is slow in all cases.

“What?? But till now, you were telling WebAssembly is faster!”

Yes, I have, but let’s understand this in more detail.

In most cases, the total Web Assembly files are more extensive than JS files (without even considering that JS files can be mainly compressed). This means that if you have a slower internet connection, then JavaScript will run faster for you. The situation may change if you are working with an extensive application in which WebAssembly is faster.

Once the WebAssembly files are cached in the browser, they load faster than the corresponding JS code, but the gain is meagre. The reason for this low gain is that JavaScript code loads and starts very quickly. WebAssembly (compiled with full optimization) is not always faster than JavaScript during execution, and when WebAssembly is faster, the gain can be small.

There might be specific tasks for which you are searching libraries in JS but not might find one. But these libraries might be present in C/C++, Rust, etc. So, WebAssembly will help tap into the new language environment.

If you find a gap in the web platform that has been filled many times in another language but not on the web or not in JS, Web Assembly might be your saviour.

Both JS and WebAssembly have the same peak performance. They are equally fast. But, it is easier to stay on the fast path with WebAssembly than it is with JS. This is primarily because of the way the WebAssembly engine works.

That’s why WebAssembly is an additional tool to go alongside JavaScript rather than its replacement.

Let’s build our first WebAssembly App!

So, after reading about WebAssembly and learning about its know-how, let’s build a simple Todo List application using WebAssembly.

For this tutorial, I will use Blazor WebAssembly, a client-side library that uses the .NET framework to build interactive Web UIs with C# instead of JavaScript.

Requirements for this project: .NET 5.0 SDK or later installed on your OS.

First, we need to make a basic structure for our web assembly project. Fortunately, Blazor provides a straightforward way to do so.

Just move to the directory where you want to create your project and open a new command line terminal in that folder. In the command line, write the following code. (Make sure you have .NET 5.0 SDK or later installed in your system)

‘dotnet new blazorserver -o TodoList’

Here the preceding name ‘TodoList’ is the name of your root directory for the project. Change directories to the TodoList folder using the command,

 cd TodoList

We want to create a new Razor component in the Pages folder (Razor is a markup syntax that lets you embed server-side code written in C# on web pages). Write the following command in your command line.

‘dotnet new razorcomponent -n Todo -o Pages’

This command will create a new Todo.razor file in the Pages folder of your project. Now let’s add our Todo component to our Navbar. Navigate to Shared/NavMenu.razor and open the NavMenu component file.

In the NavMenu.razor file, add the following block of code.

<li class="nav-item px-3">
    <NavLink class="nav-link" href="todo">
        <span class="oi oi-list-rich" aria-hidden="true"></span> Todo
    </NavLink>
</li>

In the above code, we add a NavLink for our Todo Component. Save this file. Now try to build and run this basic structure initially. In your command line, go to the root directory of your project (TodoList in this case) and type the command:

dotnet watch run

It will open your web application on the route https://localhost:5001. To Navigate to Todo Component, click on the TodoList option on the sidebar. Your web application should look like this till now:

 

As you can see, the Todo page is empty because we haven’t yet added any TodoItem. So let’s create a file in our root directory (TodoList in this case) called TodoItem.cs. Type the following C# code for the TodoItem class:

public class TodoItem
{
    public string Title { get; set; }
    public bool IsDone { get; set; }
}

Return to the Todo component (Pages/Todo.razor). Then a field for the todo items in an ‘@code’ block. The Todo component uses this field to maintain the state of the todo list. After that add an unordered list markup and a foreach loop to render each todo item as a list item (<li>).

@page "/todo"

<h3>Todo</h3>

<ul>
    @foreach (var todo in todos)
    {
        <li>@todo.Title</li>
    }
</ul>

@code {
    private IList<TodoItem> todos = new List<TodoItem>();
}

Our website will also require a UI element for adding the todo items to the list. So, add a text input and a button below the unordered list.

@page "/todo"

<h3>Todo</h3>

<ul>
    @foreach (var todo in todos)
    {
        <li>@todo.Title</li>
    }
</ul>
<!-- Input fields for adding new Todo Items -->
<input placeholder="Something todo" />
<button>Add todo</button>

Save the TodoItem.cs file and the updated Pages/Todo.razor file. As you can see in the command line, the web page automatically updates as you save any file in your project. The browser temporarily loses its connection to the app and then reloads the page when the connection is re-established.

As of now, the Add Todo button does nothing because we haven’t attached any event handler with the button. So, let’s do that.

Add an AddTodo method to the Todo component and register it for button selections using the @onclick attribute. The AddTodo C# method is called when the button is selected.

To get the new todo item’s title, add a newTodo string field at the top of the @code block and bind it to the text input value using the bind attribute in the <input> element.

Update the AddTodo method to add the TodoItem with the specified title to the list. Clear the value of the text input by setting newTodo to an empty string.

<input placeholder="Something todo" @bind="newTodo" />
<button @onclick="AddTodo">Add todo</button>

@code {
    private IList<TodoItem> todos = new List<TodoItem>();
    private string newTodo;

    private void AddTodo()
    {
        if (!string.IsNullOrWhiteSpace(newTodo))
        {
            todos.Add(new TodoItem { Title = newTodo });
            newTodo = string.Empty;
        }
    }
}

Now, if we suppose complete any task from our Todos list, we should have an option to delete them, right? So, let’s add that functionality. We will keep a checkbox to track whether the task is completed or not.

To do that, add a check box input for each todo item and bind its value to the IsDone property. Change @todo.Title to an <input> element bound to @todo.Title.

<ul>
    @foreach (var todo in todos)
    {
        <li>
            <input type="checkbox" @bind="todo.IsDone" />
            <input @bind="todo.Title" />
        </li>
    }
</ul>

How would we check whether the above conditions work or not? A straightforward solution is to add an option alongside the heading, which shows the number of todo items that aren’t complete.

<h3>Todo (@todos.Count(todo => !todo.IsDone))</h3>

The completed Todo component (Pages/Todo.razor) will look something like this:

@page "/todo"

<h3>Todo (@todos.Count(todo => !todo.IsDone))</h3>

<ul>
    @foreach (var todo in todos)
    {
        <li>
            <input type="checkbox" @bind="todo.IsDone" />
            <input @bind="todo.Title" />
        </li>
    }
</ul>

<input placeholder="Something todo" @bind="newTodo" />
<button @onclick="AddTodo">Add todo</button>

@code {
    private IList<TodoItem> todos = new List<TodoItem>();
    private string newTodo;

    private void AddTodo()
    {
        if (!string.IsNullOrWhiteSpace(newTodo))
        {
            todos.Add(new TodoItem { Title = newTodo });
            newTodo = string.Empty;
        }
    }
}

And the final Site looks like this:

 

Hurray!! You made your first Web Assembly project. See, that wasn’t hard, right? Okay, Now it is the end of the article but the start of your learning journey into this amazing and powerful technology that would revolutionize the way we use our web. Do check out the resources given below to learn more about Web Assembly.

#javascript #webassembly #wasm #webdev 

What is WebAssembly? It's the Future of Web Development

Parity Wasm: Low-level WebAssembly format Library

parity-wasm

Low-level WebAssembly format library.

Documentation

Rust WebAssembly format serializing/deserializing

Add to Cargo.toml

[dependencies]
parity-wasm = "0.42"

and then

let module = parity_wasm::deserialize_file("./res/cases/v1/hello.wasm").unwrap();
assert!(module.code_section().is_some());

let code_section = module.code_section().unwrap(); // Part of the module with functions code

println!("Function count in wasm file: {}", code_section.bodies().len());

Wabt Test suite

parity-wasm supports full wasm testsuite, running asserts that involves deserialization.

To run testsuite:

  • checkout with submodules (git submodule update --init --recursive)
  • run cargo test --release --workspace

Decoder can be fuzzed with cargo-fuzz using wasm-opt:

  • make sure you have all prerequisites to build binaryen and cargo-fuzz (cmake and a C++11 toolchain)
  • checkout with submodules (git submodule update --init --recursive)
  • install cargo fuzz subcommand with cargo install cargo-fuzz
  • set rustup to use a nightly toolchain, because cargo fuzz uses a rust compiler plugin: rustup override set nightly
  • run cargo fuzz run deserialize

no_std crates

This crate has a feature, std, that is enabled by default. To use this crate in a no_std context, add the following to your Cargo.toml (still requires allocator though):

[dependencies]
parity-wasm = { version = "0.41", default-features = false }

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in parity-wasm by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

Download Details:
Author: paritytech
Source Code: https://github.com/paritytech/parity-wasm
License: View license

#blockchain #rust #webassembly  #polkadot  #smartcontract  #substrate 

Parity Wasm: Low-level WebAssembly format Library

Wasmi: WebAssembly (Wasm) interpreter

wasmi was conceived as a component of parity-ethereum (ethereum-like contracts in wasm) and substrate. These projects are related to blockchain and require a high degree of correctness. The project is not trying to be be involved in any implementation of any of work-in-progress Wasm proposals. Instead the project tries to be as close as possible to the specification, therefore avoiding features that are not directly supported by the specification.

With all that said wasmi should be a good option for initial prototyping and there shouldn't be a problem migrating from wasmi to another specification compliant execution engine later on.

Distinct Features

The following list states some of the distinct features of wasmi.

  • Primarily concerned about
    • correct and deterministic WebAssembly execution.
    • WebAssembly specification compliance.
  • Can itself be compiled to WebAssembly.
  • Low-overhead and cross-platform WebAssembly runtime.
  • New experimental v1 engine allows to be used as a drop-in solution for Wasmtime.

Wasm Proposals

The new wasmi_v1 engine supports a variety of WebAssembly proposals and will support even more of them in the future.

Wasm ProposalStatusComment
[mutable-global] 
[saturating-float-to-int] 
[sign-extension] 
[multi-value] 
[reference-types]No support is planned for wasmi.
[bulk-memory]Planned but not yet implemented. Low priority.
[simd]No support is planned for wasmi.
[tail-calls]Not yet part of the Wasm standard but support in wasmi is planned. Low priority.

Developer Notes

Building

Clone wasmi from our official repository and then build using the standard cargo procedure:

git clone https://github.com/paritytech/wasmi.git
cd wasmi
cargo build

Testing

In order to test wasmi you need to initialize and update the Git submodules using:

git submodule update --init --recursive

Alternatively you can provide --recursive flag to git clone command while cloning the repository:

git clone https://github.com/paritytech/wasmi.git ---recursive

After Git submodules have been initialized and updated you can test using:

cargo test

Workspace

If you want to test the entire wasmi workspace using all features we recommend

cargo test --all-features --workspace

This tests both wasmi engines using all features available to them.

Note

It is recommended to test using --release since compiling and testing without optimizations usually is a lot slower compared to compiling and testing with optimizations.

Platforms

Supported platforms are primarily Linux, MacOS, Windows and WebAssembly.

Use the following command in order to produce a WebAssembly build:

cargo build --no-default-features --target wasm32-unknown-unknown

Features

Virtual Memory

On 64-bit platforms we further provide cross-platform suppport for virtual memory usage. For this build wasmi using:

cargo build --features virtual_memory

New Engine

We are currently building an experimental new wasmi engine that mirrors the Wasmtime APIs and has an improved performance and decreased overhead compared to the old wasmi engine.

You can enable and start using it today by using the wasmi_v1 workspace package:

cargo build --package wasmi_v1

Note

  • The new v1 implementation is experimental and therefore not recommended for production usage, yet.
  • Be sure to use the following Cargo profile to gain the maximum performance using the v1 engine:
[profile.release]
lto = "fat"
codegen-units = 1

Benchmarks

In order to benchmark wasmi use the following command:

cargo bench

Note: Benchmarks can be filtered by compile_and_validate, instantiate and execute flags given to cargo bench. For example cargo bench execute will only execute the benchmark tests that test the performance of WebAssembly execution.

Download Details:
Author: paritytech
Source Code: https://github.com/paritytech/wasmi
License: View license

#blockchain  #polkadot  #smartcontract  #substrate #rust #webassembly 

Wasmi: WebAssembly (Wasm) interpreter

PyScript - Python no Front-End com WebAssembly

PyScript - Python no Front-End com WebAssembly

Durante a PyCon, maior conferência internacional de Python foi anunciado o framework Pyscript que traz Python ao Frontend usando WebAssembly

00:00 - Intro - Pycon US
02:00 - Tweet do anuncio
05:00 - O que é PyScript
10:15 - Pyodide e WebAssembly
17:05 - Demonstrações
21:05 - WebGL, animações, games
22:19 - Exemplo to-do app com a tag py-list
25:19 - REPL Python rodando no Browser
27:49 - Dashboard k-means com Numpy, Pandas, Scikit Learn, Matplotlib, D3
29:17 - Finalização

#python #webassembly #wasm 

PyScript - Python no Front-End com WebAssembly

Parity's ink! to Write Smart Contracts

Parity's ink! for writing smart contracts 

ink! is an eDSL to write smart contracts in Rust for blockchains built on the Substrate framework. ink! contracts are compiled to WebAssembly.

Play with It

If you want to have a local setup you can use our substrate-contracts-node for a quickstart. It's a simple Substrate blockchain which includes the Substrate module for smart contract functionality ‒ the contracts pallet (see How it Works for more).

We also have a live testnet on Rococo called Canvas. Canvas is a Substrate based parachain which supports ink! smart contracts. For further instructions on using this testnet, follow the instructions in the our documentation.

For both types of chains the Contracts UI can be used to instantiate your contract to a chain and interact with it.

Usage

A prerequisite for compiling smart contracts is to have Rust and Cargo installed. Here's an installation guide.

We recommend installing cargo-contract as well. It's a CLI tool which helps set up and manage WebAssembly smart contracts written with ink!:

cargo install cargo-contract --force

Use the --force to ensure you are updated to the most recent cargo-contract version.

In order to initialize a new ink! project you can use:

cargo contract new flipper

This will create a folder flipper in your work directory. The folder contains a scaffold Cargo.toml and a lib.rs, which both contain the necessary building blocks for using ink!.

The lib.rs contains our hello world contract ‒ the Flipper, which we explain in the next section.

In order to build the contract just execute this command in the flipper folder:

cargo +nightly contract build

As a result you'll get a file target/flipper.wasm file, a metadata.json file and a <contract-name>.contract file in the target folder of your contract. The .contract file combines the Wasm and metadata into one file and needs to be used when instantiating the contract.

Hello, World! ‒ The Flipper

The Flipper contract is a simple contract containing only a single bool value. It provides methods to

  • flip its value from true to false (and vice versa) and
  • return the current state.

Below you can see the code using the ink_lang version of ink!.

use ink_lang as ink;

#[ink::contract]
mod flipper {
    /// The storage of the flipper contract.
    #[ink(storage)]
    pub struct Flipper {
        /// The single `bool` value.
        value: bool,
    }

    impl Flipper {
        /// Instantiates a new Flipper contract and initializes
        /// `value` to `init_value`.
        #[ink(constructor)]
        pub fn new(init_value: bool) -> Self {
            Self {
                value: init_value,
            }
        }

        /// Flips `value` from `true` to `false` or vice versa.
        #[ink(message)]
        pub fn flip(&mut self) {
            self.value = !self.value;
        }

        /// Returns the current state of `value`.
        #[ink(message)]
        pub fn get(&self) -> bool {
            self.value
        }
    }

    /// Simply execute `cargo test` in order to test your contract
    /// using the below unit tests.
    #[cfg(test)]
    mod tests {
        use super::*;
        use ink_lang as ink;

        #[ink::test]
        fn it_works() {
            let mut flipper = Flipper::new(false);
            assert_eq!(flipper.get(), false);
            flipper.flip();
            assert_eq!(flipper.get(), true);
        }
    }
}

The flipper/src/lib.rs file in our examples folder contains exactly this code. Run cargo contract build to build your first ink! smart contract.

Examples

In the examples folder you'll find a number of examples written in ink!.

Some of the most interesting ones:

  • delegator ‒ Implements cross-contract calling.
  • trait-erc20 ‒ Defines a trait for Erc20 contracts and implements it.
  • erc721 ‒ An exemplary implementation of Erc721 NFT tokens.
  • dns ‒ A simple DomainNameService smart contract.
  • …and more, just rummage through the folder 🙃.

To build a single example navigate to the root of the example and run:

cargo contract build

You should now have an <name>.contract file in the target folder of the contract.

For information on how to upload this file to a chain, please have a look at the Play with It section or our smart contracts workshop.

How it Works

  • Substrate's Framework for Runtime Aggregation of Modularized Entities (FRAME) contains a module which implements an API for typical functions smart contracts need (storage,querying information about accounts, …). This module is called the contracts pallet,
  • The contracts pallet requires smart contracts to be uploaded to the blockchain as a Wasm blob.
  • ink! is a smart contract language which targets the API exposed by contracts. Hence ink! contracts are compiled to Wasm.
  • When executing cargo contract build an additional file metadata.json is created. It contains information about e.g. what methods the contract provides for others to call.

ink! Macros & Attributes Overview

Entry Point

In a module annotated with #[ink::contract] these attributes are available:

AttributeWhere ApplicableDescription
#[ink(storage)]On struct definitions.Defines the ink! storage struct. There can only be one ink! storage definition per contract.
#[ink(message)]Applicable to methods.Flags a method for the ink! storage struct as message making it available to the API for calling the contract.
#[ink(constructor)]Applicable to method.Flags a method for the ink! storage struct as constructor making it available to the API for instantiating the contract.
#[ink(event)]On struct definitions.Defines an ink! event. A contract can define multiple such ink! events.
#[ink(anonymous)]Applicable to ink! events.Tells the ink! codegen to treat the ink! event as anonymous which omits the event signature as topic upon emitting. Very similar to anonymous events in Solidity.
#[ink(topic)]Applicable on ink! event field.Tells the ink! codegen to provide a topic hash for the given field. Every ink! event can only have a limited number of such topic field. Similar semantics as to indexed event arguments in Solidity.
#[ink(payable)]Applicable to ink! messages.Allows receiving value as part of the call of the ink! message. ink! constructors are implicitly payable.
#[ink(selector = S:u32)]Applicable to ink! messages and ink! constructors.Specifies a concrete dispatch selector for the flagged entity. This allows a contract author to precisely control the selectors of their APIs making it possible to rename their API without breakage.
#[ink(selector = _)]Applicable to ink! messages.Specifies a fallback message that is invoked if no other ink! message matches a selector.
#[ink(namespace = N:string)]Applicable to ink! trait implementation blocks.Changes the resulting selectors of all the ink! messages and ink! constructors within the trait implementation. Allows to disambiguate between trait implementations with overlapping message or constructor names. Use only with great care and consideration!
#[ink(impl)]Applicable to ink! implementation blocks.Tells the ink! codegen that some implementation block shall be granted access to ink! internals even without it containing any ink! messages or ink! constructors.

See here for a more detailed description of those and also for details on the #[ink::contract] macro.

Trait Definitions

Use #[ink::trait_definition] to define your very own trait definitions that are then implementable by ink! smart contracts. See e.g. the examples/trait-erc20 contract on how to utilize it or the documentation for details.

Off-chain Testing

The #[ink::test] procedural macro enables off-chain testing. See e.g. the examples/erc20 contract on how to utilize those or the documentation for details.

Developer Documentation

We have a very comprehensive documentation portal, but if you are looking for the crate level documentation itself, then these are the relevant links:

CrateDocsDescription
ink_langLanguage features exposed by ink!. See here for a detailed description of attributes which you can use in an #[ink::contract].
ink_storageData structures available in ink!.
ink_envLow-level interface for interacting with the smart contract Wasm executor. Contains the off-chain testing API as well.
ink_preludeCommon API for no_std and std to access alloc crate types.

Contributing

Visit our contribution guidelines for more information.

Use the scripts provided under scripts/check-* directory in order to run checks on either the workspace or all examples. Please do this before pushing work in a PR.

More relevant links:

Download Details:
Author: paritytech
Source Code: https://github.com/paritytech/ink
License: Apache-2.0 License

#blockchain  #polkadot  #substrate #ink #smartcontract #webassembly 

Parity's ink! to Write Smart Contracts
Code  Camp

Code Camp

1651157543

Blazor WebAssembly & Web API on .NET 6 – Full Course (C#)

Blazor WebAssembly & Web API on .NET 6 – Full Course (C#)

Learn Blazor WebAssembly and Web API on .NET 6 by building a shopping cart application using C#. This course also provides a guide on how to integrate a payment gateway into your Blazor WebAssembly component, so that a user is able to pay for products through your application using a debit or credit card or PayPal account.

⭐️ Course Contents ⭐️
⌨️ (0:00:00) Introduction
⌨️ (0:00:51) Create the Database using EF Core Code First Database Migrations
⌨️ (0:26:05) Retrieve Product Data from Database (Web API component)
⌨️ (0:30:17) Create Classes for Data Transfer Objects (DTOs)
⌨️ (0:36:22) Create ProductRepository Class (Repository Design Pattern)
⌨️ (0:43:05) Create ProductController Class
⌨️ (0:51:08) Create DtoConversion Class (DTO Conversion Extension methods)
⌨️ (0:57:45) Display Product Data to User (Blazor WebAssembly Component)
⌨️ (1:39:59) Display Data for Specific Product to User (Web API and Blazor)
⌨️ (2:06:07) Add Product to Shopping Cart (Web API and Blazor)
⌨️ (2:52:40) Remove Product from Shopping Cart (Web API and Blazor)
⌨️ (3:14:03) Update the Quantity of Products in the Shopping Cart (Web API, Blazor, Blazor JavaScript Interoperability)
⌨️ (3:44:01) Update the Header Menu in Response to a Change to the State of the Shopping Cart (Creating Custom Events in Blazor)
⌨️ (4:04:48) Integration of PayPal Payment Gateway into Blazor Component
⌨️ (4:36:03) Dynamically Populate the Side-Bar Menu (Web API and Blazor)
⌨️ (5:05:44) Optimise Code for Performance (Web API and Blazor)
⌨️ (5:08:26) Use Include Extension Method in LINQ Query (Web API)
⌨️ (5:14:00) User Local Storage Functionality (Blazor)
⌨️ (5:35:42) Outro

💻 Code: https://github.com/GavinLonDigital/ShopOnlineSolution 

⭐️ Resources ⭐️
🔗 Copy Seed Data from GitHub: https://github.com/GavinLonDigital/ShopOnlineSolution/blob/main/ShopOnline.Api/CodeSnippets/OnModelCreating.txt 
🔗 Download Visual Studio 2022 for Widows (Community Edition): https://visualstudio.microsoft.com/vs/ 
🔗 Download SQL Server 2019: https://www.microsoft.com/en-us/sql-server/sql-server-downloads

#blazor #webassembly #webapi #dotnet #csharp 

Blazor WebAssembly & Web API on .NET 6 – Full Course (C#)