python |
Pythonタグが付けられた新着投稿 - Qiita |
PythonでUnion-Findアルゴリズムを実装する |
https://qiita.com/84zume/items/1236a394740bc074ea78
|
このデータ構造に対して、Unionつの集合をつに統合するとFind特定の要素がどの集合に属しているかを調べるという操作を行うアルゴリズムをUnionFindアルゴリズムと呼びます。 |
2022-01-07 21:54:09 |
python |
Pythonタグが付けられた新着投稿 - Qiita |
【画像処理】NumpyでHarisのコーナー検出 |
https://qiita.com/aa_debdeb/items/6aefb8112a1347f681c9
|
ガウシアンフィルターについては以下の記事を参照してください。 |
2022-01-07 21:22:18 |
python |
Pythonタグが付けられた新着投稿 - Qiita |
poetry dev コンテナで .venv が壊れて、想定外の仮想環境再作成が行われたことへの対処 |
https://qiita.com/nassy20/items/bd84d67ca5051efc7ffa
|
poetrydevコンテナでvenvが壊れて、想定外の仮想環境再作成が行われたことへの対処発端自身のlocal環境にvenvを作成しました。 |
2022-01-07 21:16:52 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
next.jsでaddEventListener('scroll')が重複してしまいます |
https://teratail.com/questions/377108?rss=all
|
nextjsでaddEventListenerxscrollxが重複してしまいますいつもお世話になります。 |
2022-01-07 21:57:37 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
phpを再インストールしたら「curl -s “https://laravel.build/hoge” | bash」が実行できなくなった |
https://teratail.com/questions/377107?rss=all
|
phpを再インストールしたら「curls“bash」が実行できなくなったphpを再インストールの直後、「curlnbspsnbsp“nbspnbspbash」が実行しても反応がなくなってしまいました。 |
2022-01-07 21:52:23 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
npx create-nuxt-app に失敗する |
https://teratail.com/questions/377106?rss=all
|
npxcreatenuxtappに失敗する前提・実現したいことmacOSにてnuxtの新規プロジェクトを作成したい。 |
2022-01-07 21:44:21 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
C言語 離散フーリエ変換で平均値を引いて行う意図 |
https://teratail.com/questions/377105?rss=all
|
離散フーリエ変換 |
2022-01-07 21:43:55 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
mysql5.7でprepare構文をループ処理する方法について |
https://teratail.com/questions/377104?rss=all
|
aidcalcdef |
2022-01-07 21:37:26 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
FlutterでMP3をファイルに入れるとUTF-8のエラーが出ます。 |
https://teratail.com/questions/377103?rss=all
|
flutter |
2022-01-07 21:35:20 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
flutter classにてリスト作るとエラーが出ます。 |
https://teratail.com/questions/377102?rss=all
|
flutterclassにてリスト作るとエラーが出ます。 |
2022-01-07 21:19:29 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
変数結合した変数に代入できるか? |
https://teratail.com/questions/377101?rss=all
|
intidintidforintiiltiidii |
2022-01-07 21:15:58 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
機会学習で確認された特徴量から平均値や中央値、データの分布を見ることで何がわかるのか |
https://teratail.com/questions/377100?rss=all
|
機会学習で確認された特徴量から平均値や中央値、データの分布を見ることで何がわかるのかKaggleなどで行われるデータ探索について、わからないことがあったので質問いたします。 |
2022-01-07 21:14:52 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
CSSの表記が特定の場合のみ崩れる |
https://teratail.com/questions/377099?rss=all
|
CSSの表記が特定の場合のみ崩れる前提・実現したいことPHPで作成中のページに下記読込み画面を実装したところページが崩れてしまいました。 |
2022-01-07 21:05:00 |
Ruby |
Rubyタグが付けられた新着投稿 - Qiita |
【Ruby】 &. (ぼっち演算子) の使い方 |
https://qiita.com/tmasuyama/items/78bb419f5c99f0dc033d
|
irbmaingtnilampupcasegtnil注意点レシーバがnilではない時はNoMethodErrorが発生するので注意しましょう。 |
2022-01-07 21:32:07 |
Ruby |
Railsタグが付けられた新着投稿 - Qiita |
【SPA】RailsとReactとの間でsession(cookies)を扱う…?? |
https://qiita.com/NIssyi/items/d60ad466a37df240f50d
|
cookiesを受け取れるのかまずは、「どのようにすればRailsとReact間でcookiesのやり取りができるのか」について調べてみました。 |
2022-01-07 21:57:46 |
海外TECH |
MakeUseOf |
How to Determine Which Streaming Platform Is Worth Your Money |
https://www.makeuseof.com/which-streaming-platform-worth-your-money/
|
How to Determine Which Streaming Platform Is Worth Your MoneyNetflix Disney Plus HBO Max or Prime Video Here we ll discuss the important factors you need to consider before deciding on a streaming service |
2022-01-07 12:15:11 |
海外TECH |
MakeUseOf |
Why Amazon's Alexa Is Going to the Moon (Literally) |
https://www.makeuseof.com/why-amazon-alexa-going-to-the-moon/
|
literally |
2022-01-07 12:05:12 |
海外TECH |
MakeUseOf |
Does Your iPhone Charge Faster in Low Power Mode? We Found Out for You |
https://www.makeuseof.com/does-iphone-charge-faster-in-low-power-mode/
|
power |
2022-01-07 12:01:12 |
海外TECH |
DEV Community |
ETHEREAL : A Decentralized Virtual Banking system - Part II |
https://dev.to/nitdgplug/ethereal-a-decentralized-virtual-banking-system-part-ii-3ppf
|
ETHEREAL A Decentralized Virtual Banking system Part IIThis is a follow up article from our previous post ETHEREAL A Decentralized Virtual Banking system Part I Shashank Shekhar for GNU Linux Users Group NIT Durgapur・Jan ・ min read blockchain webdev beginners tutorial In the previous post we discussed the features like Creating a new account Displaying Accounts Account Details and Adding Balance Today let us learn how can we add features like Withdrawing Balance Transfer Amount to other virtual accounts on the Bank and Displaying Transaction history Part Withdrawing Balance and Transfer Amount to other virtual accounts on the BankJust navigate to SimpleStorage sol file and paste this inside Function to withdraw balance from your existing accounts the balance will be transferred to your blockchain account function withdrawBalance uint serial uint amount address payable creator external returns bool success if accounts serial balance gt amount creator transfer amount accounts serial balance amount bankBalance amount transacNum transactions transacNum Transaction transacNum accounts serial balance amount block timestamp Withdrawal serial emit TransactionCompleted amount transacNum serialNumber Withdrawal return true else revert Insufficient Funds revert InsufficientFunds serial amount accounts serial balance Withdrawal Function to virtually send money from one bank account to other function transactAmount uint amount uint serial uint serial public if accounts serial balance gt amount accounts serial balance amount accounts serial balance amount transacNum emit TransactionCompleted amount transacNum serialNumber TransferMoneySent transactions transacNum Transaction transacNum accounts serial balance amount block timestamp TransferMoneySent serial transacNum emit TransactionCompleted amount transacNum serialNumber TransferMoneyReceived transactions transacNum Transaction transacNum accounts serial balance amount block timestamp TransferMoneyReceived serial else revert Insufficient Funds revert InsufficientFunds serial amount accounts serial balance TransferMoney Now let us move on to the Front end part Now the logic for this feature is slightly counter intuitive on the frontend but pretty straightforward in the backend we create a withdrawBalance function similar to the addBalance function taking the same inputs as in the addBalance function but this function will be an external function as it also needs to access the contract balance and you cannot access the balance of a contract by being a part of the contract you need to access it from outside Withdraw balance Ether from the Contract gt Ganache account Virtual balance of both the Contract Bank and the account are decreased since actual ether is transported out of the Contract Now how to send ether from the Contract to any other ethereum account well this took a while to figure out but every address has two methods to access one is the balance method and the other is the transfer method now we use the transfer method here to transfer actual ether from the Contract to any other Ganache account here the account connected to the Metamask account Now like the previous function let us add a withdrawBalance function now according to intuition you need to subtract the amount that is passed from the frontend and one more additional line must be added to transfer actual ether from the contract to the creator address which we pass in the withdrawBalance account Now one check should be added though that the virtual account from which we are withdrawing balance should have an amount greater than the amount we want to withdraw withdrawBalance function code snippetif account serialNumber balance account serialNumber balance amount account balance amount creator transfer amount This is the syntax to transfer amount from the contract to the Ganache account connected to Metamask which is the creator accountFor the frontend let us go to our AccountDetails page let us go to another grid box whereas done in previous components we create a form input field and a submit button the value of the form input field being the withdrawBalance state variable which will be passed in the backend function On the click of the submit button we pass the withdrawBalance function on the frontend which has a similar syntax to the previous addBalance function but there are some minor differences As you can notice that the value is not given why Firstly why do we need to use the send option when we are withdrawing balance well that s the catch to access any function from the backend solidity contract you need to use the send option and it will cost some amount of ether definitely and after you approve the Metamask transaction in this case the backend function is executed and actual ether is sent from your contract to the Ganache await contract methods withdrawBalance id withdrawBalance account send from account After this you need to resolve the promise using the then and catch methods you can follow the example given in the above addBalance function where you need to run another async function to get the updated Balance and set the state of the balance variable to that updated balance You can check with your Ganache client that the amount has been added to it proving that your withdrawal was successful Now let us implement the next functionality of this module of transferring the virtual amount from one account to another the logic for this is the simplest you can find among all the previous functions as there is no actual involvement of ether The bank balance won t be increased or decreased as both the accounts are present on the bank we just need to increase the virtual balance of the account we are transferring to and decrease the virtual balance of the account from which we are sending the amount Let us quickly see the backend code for this functionality we need to create a transferAmount function which is a public function in the backend which by intuition takes inputs any guesses Well it is the amount to be transferred the serial number of the account from which the amount is being transferred and the serial number of the account to which the amount is to be transferred We need to add one check before passing the function that is the amount that is passed should be less than the balance of the account from which it is being transferred The code snippet of the transferAmount functionality is given below transferAmount code snippetif accounts serial balance gt amount accounts serial balance amount accounts serial balance amount Now let us complete the frontend code for this functionality the same old process we need to create a form in a grid box and in this form we need to take two inputs one is the second account serial number to which you need to send the amount and the other is the amount to transfer and on clicking of the submit button we need to pass a transferAmount function on the frontend This function takes the inputs from the form values and similar to the above functions we need to use the send option to run the function on the backend await contract methods transferAccount amount id secondserialNumber send from account and after this we can use the similar then and catch methods to resolve this promise and run the function to again set the balance to updated balance similar to the previous examples Part Displaying Transaction historyNavigate to SimpleStorage sol file and paste this inside Defining a struct to store transaction record struct Transaction uint transacNum uint currentBalance uint amountTransacted uint createdAt string transacType uint accountSerialNumber That concludes our project You can further customize the styling of the project and also add any more new features like substituting the serial Number with the actual account and using the account for transactions Thank you for reading this article Hope you had a great time building this project and have learned a lot more about Blockchain Technology You can find all the Resources required for this Project by clicking here Project Github repository deucaleon ETHEREAL A decentralized virtual banking system About the project This project was built with my teammates as a part of our club GNU Linux Users Group s event Ten Days of Code where we mentored students from all over India to build projects from scratch over a period of ten days This DApp is supported using Solidity Smart Contracts and the frontend is built using the framework React JS the application is deployed to the local blockchain network Ganache The whole project runs on an Ethereum supported browser with the help of the Metamask extension For building compiling and testing the written contracts Truffle was used Lastly the frontend was connected to the solidity contract using a wonderful library web The detailed guide to build this project is present in the resources folderDisplay Here are few glimpses of the project we built HOME PAGEREGISTER HEREACCOUNTS PAGEACCOUNT DETAILSTRANSFER… View on GitHubProject collaborators ltag user id follow action button background color ff important color important border color ff important Shubham Shantam RajuFollow Open Source Enthusiast Sophomore of NIT Durgapur Member of GNU Linux Users Group Full Stack Devleoper MERN Blockchain Enthusiast ltag user id follow action button background color dcc important color important border color dcc important Shashank ShekharFollow Open Source Enthusiast Junior Developer at GNU Linux User s Group NIT Dgp Full Stack developer Blockchain Fanatic ltag user id follow action button background color important color important border color important Apurva Jyoti PaulFollow Connect with us |
2022-01-07 12:19:16 |
海外TECH |
DEV Community |
ETHEREAL : A Decentralized Virtual Banking system - Part I |
https://dev.to/nitdgplug/ethereal-a-decentralized-virtual-banking-system-part-i-1mol
|
ETHEREAL A Decentralized Virtual Banking system Part IIn recent times we have all heard about Blockchain once or twice and it has been a hot and controversial topic almost in the news every other day In the parts of this article series we have explored the various terms related to Blockchain like Bitcoin Ethereum Solidity and we have built an actual working DApp a decentralized application where we have guided you in building the project from ground zero This project was built as part of our event Ten Days of Code held from th October to th October where we mentored students all over India in building projects from scratch across various domains In this project we have built a decentralized banking application now decentralized here means that the central power doesn t lie in the hands of a single user but is instead divided equally among all the users and hence no one supervises all the account in our bank and everyone is responsible for their own account We have implemented all the basic features that a bank can perform like deposition withdrawal and transfer of money Now you might be wondering why decentralized well great question indeed for this a simple analogy would suffice we all hate dictatorships where the whole power lies with a single person and hence prefer democracies well a debatable point but let s not get there now applying the same analogy wouldn t it be great if you and only you had the access to your account opposing the view of a single person having access to all the accounts being the whole purpose of this project This DApp is supported using Solidity Smart Contracts and the frontend is built using the framework React JS the application is deployed to the local blockchain network Ganache The whole project runs on an Ethereum supported browser with the help of the Metamask extension For building and compiling Truffle was used Lastly the frontend was connected to the solidity contract using a web To understand all these terms and how Blockchain works do watch the video below which was a live session from our event Ten Days of Code What is Blockchain Blockchain technology is a type of distributed ledger technology DLT ーIt is an accounting system where the ledger record of transactions is distributed among a network of computers So at its core blockchain technology is a record keeping tool Beginners guide for BlockchainWhat is a Smart Contract All of the code on the blockchain is contained in smart contracts which are programs that run on the blockchain All of the code on the blockchain is contained in smart contracts which are programs that run on the blockchain They are the building blocks of blockchain applications We ll write a smart contract in this project to power our Banking system For in depth detail click hereIntro To Solidity Solidity is the main programming language for writing smart contracts for the Ethereum blockchain It is a contract oriented language which means that smart contracts are responsible for storing all of the programming logic that transacts with the blockchain It s a high level programming language that looks a lot like JavaScript Python and C For in depth detail click here Prerequisites You can watch this video for setting up this project Ganache Local Development Blockchain The dependency is a personal blockchain which is a local development blockchain that can be used to mimic the behavior of a public blockchain We recommend using Ganache as your personal blockchain for Ethereum development It will allow you to deploy smart contracts develop applications and run tests It is available on Windows Mac and Linux as a desktop application and a command line tool Download it by clicking here For both Windows and Linux For Linux Ubuntu Users Once the download is complete go to the folder where you have downloaded the file and open the terminal and type the following to make the file executable chmod a x lt filename AppImage gt Node JSNow that you have a private blockchain running you need to configure your environment for developing smart contracts The first dependency you ll need is Node Package Manager or NPM which comes with Node js You can see if you have node already installed by going to your terminal cmd and typing node vIf you don t have a node already installed then For Windows Users Download it by clicking hereIt is recommended that you download LTS version For Linux Ubuntu Users Go to your terminal and type sudo apt install nodejs sudo apt install npmTruffle FrameworkNow let s install the Truffle Framework which provides a suite of tools for developing Ethereum smart contracts with the Solidity programming language For Windows Users Go to your cmd and type npm install g truffle For Linux Ubuntu Users Go to your terminal and type sudo npm install g truffleFor this project we have used React JS framework for the frontend and to get the required folder structure for our project we run the following command For Windows Users Go to your cmd and type truffle unbox react For Linux Ubuntu Users Go to your terminal and type sudo npx truffle unbox react Metamask WalletFor this project we would require an Ethereum wallet and here we will use the popular open source wallet Metamask On Chrome Firefox Brave It is recommended that you use Brave browser Go to the extensions page of your browser and install the Metamask plugin click hereOn installation the user will be redirected to a setup page and the user has to choose a password and a recovery phrase For in depth detail click here Getting Started with the Project After running the command npx truffle unbox react you would have a folder structure of something similar to this in front of you Let us understand what each of these means node modules This folder contains all the required npm packages for your project which are installed when you run npm install after cloning our repository src This folder contains all the components and pages for our React projectpublic This is the directory where we save our images and which also contains the main HTML file index html where all the components from src are finally rendered to give us a single page application The gitignore file contains information related code which you don t want to commit to Github The package json and package lock json are initialized when you run npm init and install npm packages in your project For in depth detail about React click hereFor React tutorial click here Must watch useState to useEffect to and React Router to Part Creating a simple blockchain project Ethereum Todo ListReferance to build this simple project Part First Functionality Creating a new accountLet us begin with the Front end Navigate to your client folder and then to src We will be writing all of our frontend code in the form of various components and import them all to the final index js file which will be rendered onto the HTML file present in the public folder Now that you have explored all the hooks used in the project we add some basic lines of code to every component to fetch all the details like web Metamask connected account and the solidity contract This code is common for all the components as we need to fetch data in every component The only component which won t contain this snippet is the Navbar because this component is only for Navigation purposes and does not require all these details for this project purposes we create a Navbar with tabs for now REGISTER and ACCOUNTS on clicking the REGISTER tab it should redirect you to the URL create you can change the name for this route if you want we have named it create and the ACCOUNTS tab should redirect you to the URL accounts You can import this Navbar in all the components you are creating to navigate to the different tabs of our application which are only currently but you will soon be creating more tabs The only modification is when you fetch more details or the particular function for that component from the contract you need to add this particular code snippet useEffect gt const getBasicDetails async gt try Get network provider and web instance const web await getWeb Use web to get the user s accounts const accounts await web eth getAccounts Get the contract instance const networkId await web eth net getId const deployedNetwork BankingContract networks networkId const instance new web eth Contract BankingContract abi deployedNetwork amp amp deployedNetwork address setWeb web setAccount accounts setContract instance catch error Catch any errors for any of the above operations alert Failed to load web accounts or contract Check console for details console error error getBasicDetails This is how your first useEffect hook looks To go through this useEffect hook once would be enough as you will be using this same useEffect hook in every component even if you create new components In this hook we have defined a function getBasicDetails where we load web from the getWeb js and we get the Metamask connected account by using web as we have already mentioned in our intro section that web acts as a connector between our backend and frontend Here we will be using web for everything For creating a new contract for using the various functions from the backend for loading accounts You will soon understand that it makes everything much easier Firstly throughout the application we use web and whenever we use web it is through asynchronous calls and we use the async await syntax and basic ES javascript then catch syntax to resolve promises web eth eth is short for ethereum is the object which contains various functions for getting your accounts getting your network id creating a new contract from your JSON file Read more about the various methods of web hereIn the getBasicDetails function we use the getAccounts net getId Contract methods of web eth getAccounts gets all the accounts connected to the Ethereum browser here Metamask to access the present connected account we want the very first element of this accounts array which is at the th index and we change the state of account variable to this net getId gets the network Id of the Solidity contract which is one of the two things to initiate a new contract using web the other one is the abi object present in the Banking json file new web eth Contract BankingContract abi deployedNetwork amp amp deployedNetwork address This initiates a contract from our existing JSON file We set the empty web variable to the loaded web object and the empty contract variable to the newly created contract using useState hook of React To give an example of the usage of the useParams hook we have used it in the Transactions component In the Transactions component we have accessed the id parameter from the URL and assigned it to a variable in the Transactions component const id useParams id In the input of the useParams hook we refer to the exact parameter variable we used in the URL in this case id I hope that helps you understand the useParams hook for more reference visit Let us briefly explore the Routing js file In the Routing js file we import Router and Route from react router dom and the basic syntax of the whole Routing component is similar for every Route import BrowserRouter as Router Route from react router dom import ComponentName from lt path to the component gt import ComponentName from lt path to the component gt lt Router gt lt Route exact path lt specify path here gt gt lt ComponentName gt lt Route gt lt Route exact path lt specify path here gt gt lt ComponentName gt lt Route gt lt Router gt The first useEffect hook will be present in all functional components like AccountDetails DisplayAccounts LoanTransaction TransferMoney and all the other components except the Navbar Let s talk about the second useEffect hook which you will be used in some or almost all of the components to extract the required functionality from the contract because only the creation of the contract is not enough We need to access the particular functionality from our contract to perform various operations for us for example when we are creating the CreateAccount js component we actually don t require any additional data but we just use the second hook to log the contract details in our browser console In this hook we run the function only when web contract and account are not undefined as we had initialized them as undefined the dependency array also has web account contract in it so that useEffect runs until all of these variables change from undefined to a definitive value this is done for easy coding purposes to view the various methods present in the contract We ll explain what are these various methods So let s continue building the createAccount js component for this we require a basic HTML form PRO TIP To build forms in which the data field values are stored in some variable which can be further used at different places we use the useState hook this has been done in all the components so I am specifying this in the beginning for your ease EXAMPLE const name setName useState lt input value name onChange e gt setName e target value placeholder Name type text gt In the above example we initialized the name variable as a blank variable and then when the form input value is changed we pass the onChange function where the state of the name variable is updated to the current target value this name can be further used any place we want overall throughout the application we use this same syntax so when I refer to making a form input with a value equal to the value of the variable x what I actually will mean is the above syntax So now if you recall from above in the Solidity contract the function to create a new account takes inputs and among those one is the creator address which is the account connected to Metamask which we already stored in the account state variable the other variables are the name and location inputs which we will get from the form that we are creating After creating the form with input fields we need to create a SUBMIT button and we need to pass a function on the click of this button now the syntax of this function will also be similar in every component and since this is for the first component let me give you the syntax EXAMPLE We defined the handleSubmit function inside our CreateAccount component but this should be above the rendering of the JSX ES arrow function syntax is being used here throughout the project you may use it or may proceed with the normal function syntax Function to handle the submit operation of the formconst handleSubmit async e gt prevents the default action that occurs when someone submits a form e preventDefault rest of the function code lt button type submit onClick handleSubmit gt SUBMIT lt button gt This function is asynchronous because we need to communicate with the contract send a request to it and wait for its response Hence we use a similar syntax everywhere using then and catch to resolve the promises more than one then can also be changed as per the user requirement Now in our createAccount js file the handleSubmit function should contain the code to access the function to create new accounts from the backend now how this is done Well firstly we have already created a new contract every contract is an object which further has an item called methods now what does this methods item contain It contains every public variable and function defined in the solidity contract That s it you can refer to the contract object in the browser console you will find the methods item in it For this component we need to access the createAccount method now there are ways to access a function using web they are call and send the major differences in these two are you use call only when you want to view data and not modify anything and it does not cost any ether to perform this transaction but if you use the send method it costs some amount of gas fees and it modifies data why does it cost ether though Well that is an interesting question though but as you already know that you need to send ether for any function to be executed or written on a new block and the miners of this block need to be rewarded somehow since they are securing the whole system by solving complex algorithms which creates new blocks for storing our executed function data hence this is the a mount deducted from our account when we use the send method which is rewarded to the miners In createAccount js we are creating a new account that is modifying data so we use the send method of web rather than the call method which is used to just view the data and the syntax of a send option is such that it also accepts another object which contains details like the from address to address and the value being sent In our banking application we deduct ETH from the Metamask account on the creation of every new account as a starting balance to the virtual account and increment the balance of the virtual account from to the increment of balance is handled on the backend await contract methods createAccount account name location send from account value web utils toWei ether then res gt console log res window location href accounts catch err gt console log err When you click on submit the Metamask will prompt you to approve the transaction with the cost of ETH on approval your new account will be created On successful approval according to the logic of the function the page will redirect to accounts This is an example of how to access any function from the backend passing the values and using the send method if you just want to display values which we will see in the DisplayAccounts js you just need to use the call method of web and spend no ether But always remember if you want to perform a function that updates the existing contract you need to spend some amount of ether and send it from your Metamask connected account the ether is sent to the contract which will in turn be sent to the miner accounts Navigate to your contracts folder and open SimpleStorage sol file SPDX License Identifier MITpragma solidity gt lt import github com Arachnid solidity stringutils strings sol contract Banking using strings for uint public serialNumber uint public transacNum uint public bankBalance Function to create account the ETH balance will be taken from your ethereum account and deposited to the banking contract function createAccount address payable creator string memory name string memory location public payable if creator balance gt serialNumber accounts serialNumber Account serialNumber block timestamp name location creator true bankBalance transacNum transactions transacNum Transaction transacNum block timestamp NewAccount serialNumber emit TransactionCompleted transacNum serialNumber NewAccount else revert Insufficient Funds revert InsufficientFunds serialNumber creator balance NewAccount Now in the src folder we further have the folder structure as gt components gt contracts gt App css gt App js gt getWeb js gt index js gt Routing js gt serviceWorker jsOnce you understand the purpose of each component you will be able to navigate easily through the code and trust me when I say organizing your code into folders is much cleaner and accessible in the future The components folder contains various sub folders for each of our components in our application here in this application we used the components gt AccountDetials the component that gets all the account details of the current account serial number gt DisplayAccounts displays all the registered accounts connected to the particular Metamask account gt DisplayTransactions displays all the transactions that occurred in the particular account gt LoanTransaction a temporarily working function that resembles loan transactions gt MainSection the main landing page when one visits the application gt Navbar used to navigate to various components gt TransferMoney the component to transfer virtual amount By looking at the names of the components you might get a feel of the job they perform you can edit the names of these components as you wish and once you edit them they will get edited in the files they were imported into The contracts folder contains the JSON file for the Banking contract we had deployed and we will be using and accessing this very JSON file to access our backend for you full stack developers out there you can imagine this as an API that can be used in your frontend application using asynchronous fetching The App js contains various imports from all the components of the application and App css defines the global styles for every component present in the application since all the components will be imported in App jsThe getWeb js is a boilerplate template generated for us by Truffle when we run the command truffle unbox react which contains a promise based function to load Web The index js is the file where the App js is finally imported and rendered onto the frontend HTML file The Routing js is an important file that contains the various routes present in the whole application it is imported from react router dom which can be installed by running the command npm install react router domLastly serviceWorker js is not of much use for us as it is just a part of the boilerplate code that appears with React That was the folder structure Now let us discuss some of the basic React hooks syntax that we have used in our application for React beginners Throughout this application we have used only three React hooks and by three I mean exactly three not more not less all the work can be done using these three hooks These are useState useEffect and useParams So let us just get to know briefly about each of these and a little bit about the project syntaxAn example for useParams is where we have imported the Transactions component to our Routing js file and in the path URL we have specified the parameter id In the Transactions component we can use this id parameter to perform actions that are specific to the account with that id we can access this id parameter in another component from the URL using the useParams hookIn the Transactions component we have accessed the id parameter and assigned it to a variable in the Transactions component const id useParams id In the bracket of the useParams hook we refer to the exact parameter variable we used in the URL I hope that helps you understand the useParams hook for more reference visit Let us briefly explore the Routing js file In the Routing js file we import Router and Route from react router dom and the basic syntax of the whole Routing component is similar for every Route import BrowserRouter as Router Route from react router dom import ComponentName from lt path to the component gt import ComponentName from lt path to the component gt lt Router gt lt Route exact path lt specify path here gt gt lt ComponentName gt lt Route gt lt Route exact path lt specify path here gt gt lt ComponentName gt lt Route gt lt Router gt Now that was all about the first useEffect hook which will be present in all functional components like AccountDetails DisplayAccounts LoanTransaction TransferMoney and every other component other than Navbar Let s talk about the second useEffect hook which you will be using in some or almost all of the components to extract the functionality from the contract because only the creation of the contract is not enough we need to access the functionality of the contract to perform various operations for us in the first component we are creating the CreateAccount js component we actually don t require any additional data but we just use the second hook to console log the contract details and in this hook we only run the function when web contract and account are not undefined as we had initialized them as undefined the dependency array also has web account contract in it so that useEffect runs until all of these variables change from undefined to a definitive value this is done for easy coding purposes to view the various methods present in the contract We ll explain what are these various methods So let s continue building the createAccount js component for this we require a basic HTML form EXAMPLE const name setName useState lt input value name onChange e gt setName e target value placeholder Name type text gt In the above example we initialized name as a blank state variable and then when the form input value is changed we pass the onChange function where the state of the name variable is updated to the current target value this name can be further used any place we want overall throughout the application we use this so when I refer to making a form input with a value equal to the value of the variable x what I actually will mean is the above syntax So now if you recall in the Solidity contract the function to create a new account takes inputs and among those one is the creator address which is the account connected to Metamask which we already stored in the account state variable the other variables are the name and location inputs which we will get from the form which we are creating After creating the form with input fields we need to create a Submit button and we need to pass a function on click of this button now the syntax of this function will also be similar in every component since it is the first component let us give you the format EXAMPLE We defined the handleSubmit function inside our CreateAccount js component but this should be above the rendering of the JSX ES arrow function syntax is being used here throughout the project you may use it or may proceed with the normal function syntax Function to handle the submit operation of the formconst handleSubmit async e gt prevents the default action that occurs when someone submits a form e preventDefault rest of the function code lt button type submit onClick handleSubmit gt SUBMIT lt button gt This function is asynchronous because we need to communicate with the contract and send a request to it and wait for its response and hence the syntax is similar everywhere using then and catch to resolve the promises more than one then can also be changed as per the user requirement Now in our createAccount js file the handleSubmit function should contain the code to access the function to create new accounts from the backend now how this is done Well firstly we have already created a new contract every contract is an object which further has an item called methods now what does this methods item contain It contains every public variable and function defined in the solidity contract That s it you can refer to the contract object in the console log you will find the methods item in it For this component we need to access the createAccount method now there are ways to access a function using web they are call and send the major differences in these two are you use call only when you want to view data and not modify anything and it does not cost any ether to perform this transaction but if you use the send method it costs some amount of gas fees and it modifies data why does it cost ether though Well that is an interesting question though but as you already know from the Basics module that you need to send ether for the function to be executed or written on a new block and the miners of this block need to be rewarded somehow since they are securing the whole system by solving complex algorithms which creates new blocks for storing our executed function data hence this is the amount deducted from our account when we use the send method which is rewarded to the miners For the createAccount js we are creating a new account that is modifying data so we use the send option and the syntax of a send option is such that it also accepts another object which contains details like the from address to address and the value being sent In our banking application we deduct ETH from the Metamask connected account on the creation of every new account as a starting balance to the virtual account and increment the balance of the virtual account from to the increment of balance is handled on the backend await contract methods createAccount account name location send from account value web utils toWei ether then res gt console log res window location href accounts catch err gt console log err When you click on SUBMIT Metamask will prompt you to approve the transaction with the cost of ETH on approval your new account will be created On successful approval according to the logic of the function the page will redirect to accounts This is an example of how to access any function from the backend passing the values and using the send method if you just want to display values which we will see in the DisplayAccounts js in the next module you just need to use the call option and spend no ether But always remember if you want to perform a function you need to spend some amount of ether and send it from your Metamask connected account the ether is sent to the contract which will in turn be sent to the miner accounts Part Displaying Accounts Account Details and Adding BalanceNow let us start coding the solidity component Just navigate to SimpleStorage sol file and paste this inside contract Banking Defining a struct to store the account details struct Account uint serial uint createdAt string name string location address creator bytes accountName uint balance bool doesExist constructor public accounts Account block timestamp Ethereal NIT Durgapur address this true Function to get the msg sender s ETH balance function getSenderBalance address payable account external view returns uint return account balance Function to get the contract s existing balance function getContractBalance external view returns uint return address this balance Function to get the owner function getOwner public view returns address return msg sender Function to add balance to your existing acccount the balance will be taken from your ethereum account function addBalance uint serial uint amount address payable creator public payable if creator balance gt amount accounts serial balance amount bankBalance amount transacNum transactions transacNum Transaction transacNum accounts serial balance amount block timestamp AddingBalance serial emit TransactionCompleted amount transacNum serialNumber AddingBalance else revert Insufficient Funds revert InsufficientFunds serial amount creator balance AddingBalance Now let us move on to the Front end part The logic for this is simple as you might have remembered we have an accounts mapping in the backend and we can access them using the serialNumber key which is the normal index of the account Here we need to use the call option and call the accounts method even mappings are part of the methods object one by one and push it into a state variable of bankingAccounts if and only if the creator of the account is the same as that of the currently connected Metamask account important check verification condition to know that the person who created the account is the only person who can access it and perform operations in it The basic layout of this component is no different from the other components but the second useEffect hook here has actual use since you need to call the accounts mapping from the contract methods and you need to call this method serialNumber the number of times serialNumber is also a method from the contract methods and check for only those accounts whose creator address is same as that of the Metamask connected account In the second useEffect hook we need to do two things we need to get the value of serialNumber and then we need to get the various accounts connected to the Metamask address and push it to the bankingAccounts state array var serial await contract methods serialNumber call even public variables from the backend need to be called Now we need to run a for loop from to less than or equal to serialNumber and call the accounts methods with the key as the value of the iterator the account object is pushed to the bankingAccounts array after it passes the check that the creator address is equal to the Metamask connected address for int i i lt serial i await contract methods accounts i call ES promise resolving syntax using then and catch then gt if res creator account setBankingAccounts bankingAccounts push name res name so on catch err gt console log err The above snippet is an example where you update the state of bankingAccounts as you are pushing each bankingAccount connected the that particular Metamask address Finally setLoading false after the whole for loop is run Now you need to use one of the famous array methods mappings in the frontend to print the contents of the bankingAccounts array to give you an idea of the CSS layout of this page it will only contain various account bars with the name and serial number which after clicking on them will redirect you to the account details page of that particular account where you can find the complete account details and various operations to perform on the account Before printing all the accounts check for if loading is false using the ternary operator and then map the bankingAccounts if the loading is still true print nothing now you need to make these bars where you are printing clickable and they should redirect you to the specific page for that account with the parameter as serialNumber to accounts id and here the usage of useParams begin as we have mentioned in the third module Also react throws you an error in the console that every child element must contain a key which is a unique identifier value so in this case also you can set the key account serial The location is changed using the window location method loading bankingAccounts map account gt lt div key account serial onClick gt window location href accounts serialNumber gt account name account serialNumber lt div gt nullNow that was displaying all the accounts we need to also keep updating the router and adding all the new routes we are creating to the router for example until now route has been occupied by createAccounts component and the accounts route is occupied by DisplayAccounts js now we add the third route accounts id for the AccountDetails js Let us begin coding the AccountDetails component As usual the two useEffect hooks are common like in every component The second useEffect hook like the previous component DisplayAccounts is not empty in it the specific account pertaining to that page is called using the id parameter from the URL and the details are stored in a state variable specifically balance item of the bankAccount is stored in another state variable so that it can easily be updated every time the balance changes for example when we add more balance or withdraw the balance const bankAccount setBankAccount useState const balance setBalance useState const id useParams id const loading setLoading useState true The function in the second useEffect hook await contract methods accounts id call then res gt console log res setBankingAccount res setBalance res balance then gt setLoading false catch err gt console log err Now we have the data stored in our state variables we just display it somewhere on our application To give a brief idea of the layout of the page let us divide the page into various columns one in the extreme left to print the account details there are various other grid boxes for each functionality that contain a simple form for example there is an additional balance grid box a withdraw balance grid box a transfer amount grid box and a box for transferring amount from one account to other later we can add more grid boxes which contains buttons that redirect to pages for displaying transaction last extras section and the other one for performing loan transactions Now let us move on to the second part of this article and create a function in the backend to add virtual balance to our bank account We create a public payable addBalance function which takes inputs as the serial amount and the creator address Why these inputs Serial number is required to increase the virtual balance of that particular virtual account The amount is the amount to be passed that is to be added You need the creator address that is connected to Metamask to transfer actual ether from your Ganache account We need to increase the virtual balance by accessing the balance item of the particular account from the serialNumber and we also need to increase the bankBalance of the whole application present at the th index of the accounts mapping We need to also add a check to only update the virtual balance when the Metamask connected Ganache account balance is greater than the amount entered Add balance code snippet if creator balance gt amount account serialNumber balance amount account balance amount Now after displaying the account details we start coding the add balance functionality grid box on the frontend it should contain a form input with the state variable balanceAdded as we have specified in previous examples and also a submit button which onClick should fire an addBalance function which is similar to the syntax of our previous functions and should take the input values We use the send method here and the from address is from the Metamask account and the value is the balance to be added which should also be passed in the object We need to pass this value in the send method since that amount of ether should be transferred from our Ganache account to the contract if we don t specify the amount only a minimal amount of ether will be costed that will be the gas amount to perform the function from the backend Adding Balance Ether from Ganache gt Contract AddressVirtual Balance of the account and Contract Bank are both increased since actual Ether flows from the Contract We have to also again call the accounts method with the key serial number and then update the balance variable to instantly print the new balance in the account details grid section const addBalance async e gt e preventDefault The addBalance is the state variable which we get from the addBalance form and the account is the Metamask connected account await contract methods addBalance id addBalance account send from account value addBalance then res gt console log res then async gt await contract methods accounts id call then res gt setBalance res balance catch err gt console log err catch err gt console log err We have completed the first functionalities of our virtual bank namely Creating a new account and Updating the Balance for the account in this article in the nd part of this article series we will be adding features like Withdrawing Balance Transfering Amount to other virtual accounts on the Bank and Displaying Transaction history of an account to our virtual bank This is a nd Part of this article in which we will be adding features like Withdrawing Balance Transfer Amount to other virtual accounts on the Bank and Displaying Transaction history to our Project ETHEREAL A Decentralized Virtual Banking system Part II Shashank Shekhar for GNU Linux Users Group NIT Durgapur・Jan ・ min read blockchain webdev beginners tutorial You can find all the Resources required for this Project by clicking here Project Github repository deucaleon ETHEREAL A decentralized virtual banking system About the project This project was built with my teammates as a part of our club GNU Linux Users Group s event Ten Days of Code where we mentored students from all over India to build projects from scratch over a period of ten days This DApp is supported using Solidity Smart Contracts and the frontend is built using the framework React JS the application is deployed to the local blockchain network Ganache The whole project runs on an Ethereum supported browser with the help of the Metamask extension For building compiling and testing the written contracts Truffle was used Lastly the frontend was connected to the solidity contract using a wonderful library web The detailed guide to build this project is present in the resources folderDisplay Here are few glimpses of the project we built HOME PAGEREGISTER HEREACCOUNTS PAGEACCOUNT DETAILSTRANSFER… View on GitHubProject collaborators ltag user id follow action button background color ff important color important border color ff important Shubham Shantam RajuFollow Open Source Enthusiast Sophomore of NIT Durgapur Member of GNU Linux Users Group Full Stack Devleoper MERN Blockchain Enthusiast ltag user id follow action button background color dcc important color important border color dcc important Shashank ShekharFollow Open Source Enthusiast Junior Developer at GNU Linux User s Group NIT Dgp Full Stack developer Blockchain Fanatic ltag user id follow action button background color important color important border color important Apurva Jyoti PaulFollow Connect with us |
2022-01-07 12:07:08 |
Apple |
AppleInsider - Frontpage News |
Dropbox finally testing native Apple Silicon version |
https://appleinsider.com/articles/22/01/07/dropbox-finally-testing-native-apple-silicon-version?utm_medium=rss
|
Dropbox finally testing native Apple Silicon versionAs Apple enters what is likely the last stretch of its two year transition from Intel to Apple Silicon cloud file sync company Dropbox is at last testing a native version Tim Cook announced Apple Silicon in June Apple also began issuing Developer Transition Kits that same month From then until around a year later in June the Dropbox company ignored questions about its moving to Apple Silicon It most noticeably ignored the growing number of people asking in its own support forums Read more |
2022-01-07 12:29:43 |
Apple |
AppleInsider - Frontpage News |
Rooney Mara to star as Audrey Hepburn in Apple TV+ biopic |
https://appleinsider.com/articles/22/01/07/rooney-mara-to-star-as-audrey-hepburn-in-apple-tv-biopic?utm_medium=rss
|
Rooney Mara to star as Audrey Hepburn in Apple TV biopicApple TV has secured another high profile feature film an as yet untitled Audrey Hepburn biography starring Rooney Mara of The Girl with the Dragon Tattoo Rooney Mara source Wiki Commons Apple Studios has continued adding to its production slate with the Hepburn movie to be directed by Luca Guadagnino Best known for the film Call Me by Your Name Guadagnino also directed documentaries including a biographical one of Bernardo Bertolucci Read more |
2022-01-07 12:04:59 |
医療系 |
医療介護 CBnews |
医療逼迫時、派遣可能な医師・看護師は各3千人-政府、円滑な病床稼働へ |
https://www.cbnews.jp/news/entry/20220107210325
|
新型コロナウイルス |
2022-01-07 21:10:00 |
金融 |
RSS FILE - 日本証券業協会 |
協会員の異動状況等 |
https://www.jsda.or.jp/kyoukaiin/kyoukaiin/kanyuu/index.html
|
異動 |
2022-01-07 13:00:00 |
金融 |
金融庁ホームページ |
人事異動(令和4年1月7日発令)を掲載しました。 |
https://www.fsa.go.jp/common/about/jinji/index.html
|
人事異動 |
2022-01-07 14:00:00 |
ニュース |
BBC News - Home |
Kazakhstan unrest: Troops ordered to fire without warning |
https://www.bbc.co.uk/news/world-asia-59907235?at_medium=RSS&at_campaign=KARANGA
|
kazakhstan |
2022-01-07 12:15:25 |
ニュース |
BBC News - Home |
Covid in Wales: Those calling for restriction ease are 'wrong' - FM |
https://www.bbc.co.uk/news/uk-wales-59895505?at_medium=RSS&at_campaign=KARANGA
|
cases |
2022-01-07 12:55:52 |
ニュース |
BBC News - Home |
Boris Johnson under fire over Tory donor's Great Exhibition plan |
https://www.bbc.co.uk/news/uk-politics-59906637?at_medium=RSS&at_campaign=KARANGA
|
favours |
2022-01-07 12:41:32 |
ニュース |
BBC News - Home |
Edward Colston statue case could be sent to appeal court |
https://www.bbc.co.uk/news/uk-england-bristol-59909823?at_medium=RSS&at_campaign=KARANGA
|
acquittal |
2022-01-07 12:08:02 |
ニュース |
BBC News - Home |
Cars stuck on main roads as snow causes disruption across Scotland |
https://www.bbc.co.uk/news/uk-scotland-59906385?at_medium=RSS&at_campaign=KARANGA
|
scotland |
2022-01-07 12:21:37 |
ニュース |
BBC News - Home |
CES 2022: Colour changing cars and remotes that eat wi-fi |
https://www.bbc.co.uk/news/technology-59895079?at_medium=RSS&at_campaign=KARANGA
|
colour |
2022-01-07 12:11:32 |
サブカルネタ |
ラーブロ |
自家製特粉うどんそのさき@南古谷(鍋焼きうどん) |
http://ra-blog.net/modules/rssc/single_feed.php?fid=195324
|
鍋焼きうどん |
2022-01-07 12:10:00 |
北海道 |
北海道新聞 |
乳牛初競り、価格低め ホクレン市場 生乳生産抑制で需要減 |
https://www.hokkaido-np.co.jp/article/631139/
|
音更 |
2022-01-07 21:18:00 |
北海道 |
北海道新聞 |
ラッシーを牛乳消費拡大の切り札に 本別のカレー店が無料提供 |
https://www.hokkaido-np.co.jp/article/631137/
|
新型コロナウイルス |
2022-01-07 21:16:00 |
北海道 |
北海道新聞 |
80代女性が3400万円だまし取られる 札幌白石署 |
https://www.hokkaido-np.co.jp/article/631136/
|
札幌市白石区 |
2022-01-07 21:15:00 |
北海道 |
北海道新聞 |
コロナ自宅療養者、1週間で倍増 全国1168人、増加傾向に |
https://www.hokkaido-np.co.jp/article/631135/
|
厚生労働省 |
2022-01-07 21:14:00 |
北海道 |
北海道新聞 |
JR、7日12本運休し千人に影響 8日も6本運休 |
https://www.hokkaido-np.co.jp/article/631132/
|
普通列車 |
2022-01-07 21:12:00 |
北海道 |
北海道新聞 |
米艦の小樽寄港、米側に再考要請へ 知事表明 週明けにも小樽、札幌両市と |
https://www.hokkaido-np.co.jp/article/631129/
|
記者会見 |
2022-01-07 21:09:00 |
北海道 |
北海道新聞 |
ワカサギ釣れたよ! 網走湖2会場で解禁 |
https://www.hokkaido-np.co.jp/article/631127/
|
道内 |
2022-01-07 21:07:00 |
北海道 |
北海道新聞 |
首相、3県へのまん防適用決定後に会見せず |
https://www.hokkaido-np.co.jp/article/631126/
|
岸田文雄 |
2022-01-07 21:06:00 |
北海道 |
北海道新聞 |
観光客4.2%減601万人 後志管内21年度上半期 自粛や入国制限が影響 |
https://www.hokkaido-np.co.jp/article/631125/
|
後志総合振興局 |
2022-01-07 21:07:00 |
北海道 |
北海道新聞 |
後志管内18市町村、週末に成人式 変異株警戒、小樽は分散 式後の直帰呼び掛けへ |
https://www.hokkaido-np.co.jp/article/631124/
|
新型コロナウイルス |
2022-01-07 21:04:00 |
北海道 |
北海道新聞 |
無病息災、火と煙に託し 函館の社寺でどんど焼き |
https://www.hokkaido-np.co.jp/article/631123/
|
函館市内 |
2022-01-07 21:03:00 |
北海道 |
北海道新聞 |
年末年始の牛乳消費、道内は5%増 Jミルク |
https://www.hokkaido-np.co.jp/article/631121/
|
年末年始 |
2022-01-07 21:01:00 |
ビジネス |
東洋経済オンライン |
中国でレアアース「新・国策企業」が発足の背景 大手3社が合併、業界全体の競争力向上目指す | 「財新」中国Biz&Tech | 東洋経済オンライン |
https://toyokeizai.net/articles/-/479910?utm_source=rss&utm_medium=http&utm_campaign=link_back
|
biztech |
2022-01-07 21:30:00 |
仮想通貨 |
BITPRESS(ビットプレス) |
[日経] ビットコインに地政学リスク カザフ混乱で急落 |
https://bitpress.jp/count2/3_9_12979
|
混乱 |
2022-01-07 21:50:58 |
コメント
コメントを投稿