Автор оригинала: Honey Thakuria.
Существует постоянно растущий интерес и спрос на разработку децентрализованного заявления (DAPP). Поэтому я решил придумать учебник, чтобы помочь вам начать с разработкой и архитектурой модульного DAPP. Мы будем использовать один из самых популярных и широко распространенных языков 21-го века: JavaScript.
Мы будем работать со следующими технологиями в этом руководстве:
- Небулас : платформа Blockchain, которая позволяет нам писать умные контракты в JavaScript. Регистрация здесь получить реферальную пользу.
- Nuxt. JS : рамки, построенные на вершине Vue. Js. .
- Небпай : Платеж небулас JavaScript API. Как для ПК, так и для мобильных.
- WebextensionWallet : Используется для взаимодействия с умным договором для платежных целей.
Я буду объяснять процесс создания DAPP с помощью существующего DAPP, Распределенные истории Отказ Это квалифицировано для новой награды Дапп в 1 сезон Программы стимулирования на Платформа Небулс Отказ
Вы можете найти исходный код для Frestend Of Daapp здесь Отказ Код Smart Contract можно найти в PayLoaddata здесь Отказ
Не всегда достаточно, чтобы узнать о создании простого приложения для TO-DO. Иногда мы также должны понимать, как архитектора больших модульных приложений.
Сосредоточиться на таком приложении, я дам вам обзор высокого уровня структурирования большого модульного DAPP с использованием NUXT.JS и NEBULAS. Вы можете получить более подробную глубину, исследуя и отладки совместно используемого выше.
Что мы собираемся построить?
Мы собираемся создать короткий история / стихотворение Сотрудничество, распределенные истории. Это позволит пользователю создавать новую историю, добавив линию в существующую историю и разделяя историю в Twitter. Вот демонстрация ссылка Отказ
Я буду объяснять Умный контракт и Архитектура Frontend в предстоящих линиях.
Умный Код Контракта
Frontend DAPP сообщает с SmartContract, чтобы получить и записать данные. Тогда платформа BlockChain, которая синхронизирует этот умный контрактные данные по нескольким узлам, чтобы соответствовать потребностям децентрализации и безопасности. Этот процесс синхронизации требует немного времени, и поэтому процесс записи затратывает время и деньги в форме NAS.
Инициализация истории
В разделе «Ниже» я объясню вам часть интеллектуального контракта, который определяет объект истории:
"use strict";
/*
Story Constructor which will create the story by providing the necessary field fetched from the frontend using nebpay API explained at the end of this blog:
*/
var Story = function(text, image_url) {
this.title = text;
this.address = Blockchain.transaction.from;
this.hash = Blockchain.transaction.hash;
this.image_url = image_url;
this.lines = [];
this.votes = [];
};
/*
Init function is used once while deploying the smart contract to
initialize the parameters if required:
*/
Story.prototype = {
init: function() {
}
};Как упомянуто выше, каждая история будет иметь следующие поля, из которых текст и Image_URL необходимо предоставить в качестве аргумента пользователя. Для поля адреса хеш может быть получен с использованием блокчанских API, объясненных в глубине здесь Отказ
Структура данных и хранение, используемые в DAPP
Модуль хранения позволяет хранить хранилище данных на небуласах. Это позволяет постоянно хранить переменные данных на небулах, когда платеж производится. Вы можете прочитать глубину об этом здесь Отказ
/*
With the help of the Storage Module, we are defining following maps and index property, which will help us to keep track of multidimensional data obtained from users. Nebulas recommend the capturing of multiple data points, which may help in improving Nebulas Rank and Search Feature.
*/
var Data = function() {
LocalContractStorage.defineMapProperty(this, "favourite_stories");
LocalContractStorage.defineMapProperty(this, "my_stories");
LocalContractStorage.defineProperty(this, "s_index");
LocalContractStorage.defineMapProperty(this, "stories_data");
};Сохранение и извлечение истории
Теперь мы посмотрим на две из самых важных функций, используемых для написания и получения истории на платформе с помощью конструктора истории и хранилища, объявленные в конструкторе данных выше.
/*
stories_data hash map will contain every story stored against its unique index on the Platform storage module.
Every story index added by a particular user will be stored in a hash map my_stories, in the form of an array.
*/
Data.prototype = {
/*
Initializing the index on Smart Contract. As soon as people will keep on adding a new story, s_index will keep on increasing.
*/
init: function () {
this.s_index = new BigNumber(1);
},
save_story: function (name, image_url) {
var id = this.s_index;
if (name.length > 25) {
throw new Error("Story Length error");
}
if (name == "") {
throw new Error("empty story title");
}
var story = new Story(name, image_url);
this.stories_data.put(new BigNumber(id).toNumber(), JSON.stringify(story));
var my_stories_local = this.my_stories.get(Blockchain.transaction.from) || [];
my_stories_local.push(this.s_index);
this.my_stories.put(Blockchain.transaction.from, my_stories_local);
this.s_index = new BigNumber(id).plus(1);
},
/*
get_stories method will be used to retrieve all the stories stored on the platform.
*/
get_stories: function () {
var stories = [];
var total = new BigNumber(this.s_index).toNumber();
for (let i = 1; i < total; i++) {
stories.push(JSON.parse(this.stories_data.get(i)));
}
return stories;
},
/*
Remaining Functions can be found out in the Smart Contract Code here.
*/
};
module.exports = Data;Это завершает основные части интеллектуального контракта. В следующем разделе я объясню структуру кода Frontend в nuxt.js.
Дизайн архитектуры Frontend
По мере роста проекта и дополнительные функциональные возможности добавляются, правильная архитектура, созданная с самого начала, может помочь нам достичь нашей цели, облегчая отладку.
Ниже подход – хороший способ пойти в это:
/*
Go to the root directory in the source code here and find out the below-mentioned files. This Architecture helps in creating a big modular App/Dapp.
*/
pages/
about / index.vue : Static About us PAge
contact / index.vue : Static Contact us Page
create / index.vue : Page to Create the Story.
favourite / index.vue : Stories Liked by you will be here.
mystory / index.vue : My Stories Page.
index.vue / index.vue : All Stories Page
store/
index.js : Vuex code used to make API calls to Smart Contract
neb_init.js : Importing nebpay and initializing Smart Contract
Address here, which gets used throughout the app.
layouts/
default.vue: Every page follows an architecture where Header and
Footer are same. So setting up the default
architecture here.
components/
Header.vue: Header component which is getting used in default.vue
Footer.cue: Footer component which is getting used in default.vue
....Создание API призывает к умного договору
Я буду объяснять один из вызов API, используя Небпай Взаимодействовать с умным договором и получить все данные историй для посадочной страницы.
Инициализировать NEBPay, который будет использоваться через приложение в магазин/neb_init.js. :
import * as NebPay from 'nebpay.js';
/*
Contract Address can be obtained after deploying the code on Nebulas Platform using their Web Wallet.
It needs to be the Mainnet Address.
*/
var contractAddress = "n1pQHv...................Pm1";
var nebPay = new NebPay();
export { contractAddress, nebPay, result,NebPay };Ниже API звонок Код можно найти в магазин/index.js файл:
/*
nebPay API's can be used to interact with the Smart Contract and Chrome extension to perform read and write operations. More details about nebpay API's can be found out here.
*/
call: (store) => {
// args needs to be sent in below format.
var args = "[]";
nebPay.simulateCall(contractAddress, 0, "get_stories", args, {
listener: function (data) {
if (data.result != null) {
store.commit("all_data", JSON.parse(data.result));
}
}
});
}Приведенный выше код называется Компонент/allstories.vue Отказ
/*
As soon as the Allstories component gets mounted, it dispatches the call action mentioned in the above lines, which then fills the Vuex Store all_data array and gets rendered in the All Stories Component.
*/
mounted() {
this.$store.dispatch("call");
}Таким образом, вы можете обойти каждый раздел в исходном коде и понять полную архитектуру DAPP.
Я надеюсь, что этот учебник помог вам начать работу с разработкой DAPP. Для любых запросов не стесняйтесь обращаться ко мне.
Оригинал: “https://www.freecodecamp.org/news/architecting-dapp-using-nuxt-js-nebulas-fc00712ae341/”