Building React front end for etherum solidity smart contract - reactjs

I am new to react and solidity however I am doing one project for just learning but I am unable to understand how to create react front end of Solidity project.
pragma solidity^0.5.0;
pragma experimental ABIEncoderV2;
contract I2Chain {
event FileChained(string checksum,
address indexed user,
uint timestamp,
uint fileSize,
uint fileTimestamp,
string fileType,
string fileName);
event FileShared(string checksum,
address indexed user,
address indexed recipient,
uint attributes,
uint tenure,
uint timestamp);
event FileRead(string checksum, address indexed user, uint timestamp);
event FileDeleted(string checksum,
address indexed user,
uint timestamp);
event PubKeyUpdate(address indexed user, string pubKey);
mapping(address => string) public publicKeys;
function PublishFile(string memory _checksum,
uint _fileSize,
uint _fileTimestamp,
string memory _fileType,
string memory _fileName)
public {
emit FileChained(_checksum, msg.sender, now,
_fileSize,_fileTimestamp, _fileType, _fileName);
}
function ShareFile(string memory _checksum, address _recipient,
uint _attributes,
uint _tenure) public {
emit FileShared(_checksum, msg.sender, _recipient, _attributes,
_tenure, now);
}
function ReadFile(string memory _checksum) public {
emit FileRead(_checksum, msg.sender, now);
}
function DeleteFile(string memory _checksum) public {
emit FileDeleted(_checksum, msg.sender, now);
}
function setPublicKey(string memory _pubKey) public {
publicKeys[msg.sender] = _pubKey;
emit PubKeyUpdate(msg.sender, _pubKey);
}
function getPublicKey(address _user)
view public returns(string memory) {
return publicKeys[_user];
}
}
I have deployed the contract into truffle and generate the ABI of contract, however I didn't understand how to create the front-end with this ABI.
Note:p
When I deployed into remix IDE I am getting all function interface(please see the attachement enter image description here
Please suggest and help me how can I create UI for this contracts all function so user can intact with my smart contract and blockchain?

If you're new to both, i think you should follow this tutorial where they use drizzel to connect the blockchain with the frontend.
https://truffleframework.com/tutorials/getting-started-with-drizzle-and-react

Related

Error searching in map using array in Solidity

I want to have a network of clients and servers in this network. To connect to the edge servers, the clients first check the validity of the edge server and then connect to it, and the client also connects to the said edge. . The client calculates the credibility of this edge server. In this code, I want to calculate the reputation of the edge server, so I have mapped the address of the edge server and the client to the reputation and used an identifier to search. I get an error when I run the ComputeReputation function.
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;
import "https://github.com/PaulRBerg/prb-math/blob/v1.0.3/contracts/PRBMathSD59x18.sol";
contract Reputationcalculation{
using PRBMathSD59x18 for int256;
struct edgeserver{
bool exists;
uint placed_bids;
uint reputation;
uint deposit;
}
mapping (address => edgeserver) public edgeserver_suppliers;
struct mobileuser{
bool exists;
uint deposit;
//credbility
bool auction_open;
}
mapping (address => mobileuser) public mobileusers;
mapping(address => mapping(address =>mapping (uint=>uint))) public reputation;
mapping(uint => edgeserver) public listedgeservers;
mapping(address => mapping(address => uint)) public reputationid;
//mapping (uint => address) public mobile_user;
//mapping (uint => address) public edge_server;
address payable private owner;
address[] public mobile_user;
address[] public edge_server;
uint SIC;
uint n;
uint u;
uint s;
address client;
address server;
uint reputationSum ;
//uint numRatings;
uint id=0;
uint reputationlength;
uint reputationAverage;
modifier onlyOwner{
require(msg.sender == owner,"Sender not authorized.");
_;
}
modifier onlyClient{
require(mobileusers[msg.sender].exists,"Sender not authorized.");
_;
}
modifier onlySupplier{
require(edgeserver_suppliers[msg.sender].exists,"Sender not authorized.");
_;
}
event edgeserverRegistered(address supplierAddress);
event mobileuserRegistered(address clientAddress);
constructor () public{
owner =payable( msg.sender);
n=0;
SIC=0;
u=0;
s=0;
reputationSum = 0;
//numRatings = 0;
reputationlength=0;
reputationAverage=0;
// client=msg.sender;
}
function addmobileuser() payable public{
require(!mobileusers[msg.sender].exists,"mobileuser already registered");
require(!edgeserver_suppliers[msg.sender].exists,"Address registerd as a edgeserver");
mobileusers[msg.sender]=(mobileuser(true,msg.value,false));
client=msg.sender;
u++;
emit mobileuserRegistered(msg.sender);
}
function addedgeserver(address supplier) onlyOwner public{
require(!mobileusers[supplier].exists,"Address registerd as a mobile user");
edgeserver_suppliers[supplier]=(edgeserver(true,0,0,0));
server=msg.sender;
s++;
emit edgeserverRegistered(supplier);
}
function SetReputation(address mobile, address edge, uint rating) public {
mobile_user.push(mobile);
edge_server.push(edge);
reputation[mobile][edge][id]= rating;
id++;
reputationlength=id;
}
function ComputeReputation(address user )public {
uint numRatings = 0;
address mobile;
address edge;
for(id=0;id<=reputationlength;id++)
{
mobile=mobile_user[id];
edge=edge_server[id];
if(user==mobile){
reputationSum += reputation[mobile][edge][id];
numRatings++;
}
}
}
function getReputation( ) public returns(uint )
{
reputationSum;
}
}
Please help. Thank you
Actually, my problem is searching in the map. I want to calculate the total reputation given to each edge server by a specific client. Also, later, I plan to calculate the total reputation given by each client to a specific server. Please help me.

Timed Advertisements Solidity Contract

Basically, I'm trying to make the smart contract be able to take exactly 0.05 eth ONLY when the cooldown timer is set to 0. The Dapp I'm creating is a first come first serve eth advertising service, where the user can upload an image or gif within the dapp, then pay 0.05 eth to trigger the advertisement to run for x amount of time. When the time runs out, the next user can purchase their ad slot.
The timer seems to work, but I cant get the timer to start upon payment.
I would really appreciate the help, here is what I have so far:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract AdEth {
//This sets up the name of the ad and if it is running, set to false by default
//Variables for start, end, cooldown (cool down can be changed here)
address payable public owner;
uint _start;
uint _end;
uint cooldownTime = 1 minutes;
constructor() {
owner = payable(msg.sender);
}
modifier timerOver {
require(block.timestamp <= _end, "The Cooldown is over");
_;
}
modifier onlyWhileOpen {
require(block.timestamp >= _start && block.timestamp <= _end);
_;
}
function start() public {
_start = block.timestamp;
end(cooldownTime);
}
function end(uint totalTime) public {
_end = totalTime + _start;
}
function getTimeLeft() public view returns(uint) {
return _end - block.timestamp;
}
receive() external payable {
}
function receiveAdPayment() payable public returns (bool) {
require(msg.value == 0.05 ether, "Not enough ether. 0.05 Needed.");
require(cooldownTime == 0, "There is currently an add running. Please wait until the cooldown is finished.");
msg.sender.transfer(0.05 ether);
start();
return true;
}
function withdrawAll(uint _amount) external {
require(msg.sender == owner, "Caller is not the owner.");
payable(msg.sender).transfer(_amount);
}
function getBalance() external view returns (uint) {
return address(this).balance;
}
}
------------EDITS 5.11.21--------------
I have swapped out all of the timestamps for block.number and everything is working as intended. However, I want the smart contract to automatically call the setRunning() function when the cooldownTime expires. Is this possible? or is this the best its going to get?
Appreciate any and all help!
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract AdEth {
//This sets up the name of the ad and if it is running, set to false by default
//Variables for start, end, cooldown (cool down can be changed here)
address payable public owner;
uint _start;
uint _end;
//The number is in BLOCKS (~15 sec each, rinkeby approx ~1 min)
uint cooldownTime = 4;
bool running;
constructor() {
owner = payable(msg.sender);
}
function start() internal {
_start = block.number;
_end = block.number + cooldownTime;
running = true;
}
function getTimeLeft() public view returns(uint) {
return _end - block.number;
}
//This allows the owner to set "running" to false only if the required amount of cooldown blocks is reached.
function setRunning() public {
require(msg.sender == owner, "You are not the owner.");
require(block.number > _end, "Wait for the cooldown to expire before you can reset running to false.");
running = false;
}
function isRunning() public view returns (bool) {
return running;
}
function receiveAdPayment() payable public {
require(msg.value >= 0.05 ether, "At Least 0.05 ETH Needed.");
require(block.number > _end, "There is currently an ad running. Please wait until the cooldown is finished.");
require(running != true, "The ad time may have run out, but has not been reset by Admin.");
start();
}
function withdraw(uint _amount) external {
require(msg.sender == owner, "Caller is not the owner.");
payable(msg.sender).transfer(_amount);
}
function getBalance() external view returns (uint) {
return address(this).balance;
}
}
----EDITS 5.18.22------
Ok here is the final product. Got pushed in a bunch of directions and chose the below code. It is working well in remix.
Thanks everyone!
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import '#openzeppelin/contracts/access/Ownable.sol';
contract AdEth is Ownable {
//This sets up the name of the ad and if it is running, set to false by default
//Variables for start, end, cooldown (cool down can be changed here)
uint _start;
uint _end;
uint cooldownTime = 3 minutes;
uint runNumber = 0;
function start() internal {
_start = block.timestamp;
_end = block.timestamp + cooldownTime;
runNumber++;
}
function getTimeLeft() public view returns(uint) {
return _end - block.timestamp;
}
function adRunNumber() public view returns (uint) {
return runNumber;
}
function receiveAdPayment() payable public {
require(msg.value >= 0.05 ether, "At Least 0.05 ETH Needed.");
require(block.timestamp > _end, "There is currently an ad running. Please wait until the cooldown is finished.");
start();
}
function withdraw(uint _amount) external onlyOwner {
payable(msg.sender).transfer(_amount);
}
function getBalance() external view returns (uint) {
return address(this).balance;
}
}
First thing: NEVER use block.timestamp. It's not validated and can be abused. Use the block number as a form of timestamp instead.
Second thing: start() should be internal. Currently, anyone can call this, and this does not seem to be intentional behavior.
Finally, your issue: It appears you have two payable methods. The first one is the one that will be called. Remove the receive() function.

Persistence with EJB3 doesn't work

I have a method to save a new object in an EJB bean. This method is called, without error, but nothing changes in the database. I can't understand why.
Here is the code:
#Stateless(name = "Ar", mappedName = "ManagementBean")
public class ManagementBean implements IManagementBeanLocal, IManagementBeanRemote {
...
#Override
public int storeRawSms(String raw, String requestUid, String text, String service, boolean correctlyAnalysed, Date receivedTimestamp,
boolean toBeAnalysed, String phoneNumber) {
// Get phone number, create if it dosn't exist
PhoneNumber pn = getOrCreatePhoneNumberPrivate(phoneNumber);
// Create rawSMS
RawSms rawSms = new RawSms(raw, requestUid, text, service, correctlyAnalysed, receivedTimestamp, toBeAnalysed, pn);
// Store and return result
em.persist(rawSms);
int result = rawSms.getId();
em.flush();
em.clear();
return result;
}
...
And the caller:
#PersistenceContext private EntityManager em;
...
int rawSmsIs = bean.storeRawSms(raw, requestUid, message, service, false, new Date(), true, sender);
Do you have an idea?
I see that you inject a reference to the EntityManager in the client (not sure why), but I don't see it in the session bean (maybe simply because you did not include the line in your message). Is it possible that you forgot to use the annotation #PersistenceContext in your stateless session bean?
Also, be careful: depending on the JPA implementation you are using and the generation strategy for the ids, you should call flush() before calling getId(). Indeed, if you let the DB generate your IDs, then you need a flush() to have this happen before the method returns the value.
Thanks, the prposed solution worked!
I use the container-managed transactions like this:
#Stateless(name = "Ar", mappedName = "ManagementBean")
#TransactionManagement(TransactionManagementType.CONTAINER)
public class ManagementBean implements IManagementBeanLocal, IManagementBeanRemote {
....
#Override
#TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public int storeRawSms(String raw, String requestUid, String text, String service, boolean correctlyAnalysed, Date receivedTimestamp, boolean toBeAnalysed, String phoneNumber) {
....
Thanks again!
It seems that your transaction never commited, so try changing transaction management:
#Stateless(name = "Ar", mappedName = "ManagementBean")
#TransactionManagement(TransactionManagementType.BEAN)
public class ManagementBean implements IManagementBeanLocal, IManagementBeanRemote {
#Resource
private UserTransaction utx;
#Override
public int storeRawSms(..) {
try {
utx.begin();
..
em.persist(rawSms);
int result = rawSms.getId();
utx.commit();
}
catch(Exception ex) {
//EXCEPTION HANDLING
utx.rollback();
}
}
}

marshal delegate to function pointer: memory corrupt

public class SendImage
{
public delegate int DWatch(int bytesLeftToSend, IntPtr Response);
ret=0xffff;
public void ReadImageFile()
{
int len = 1495;
DWatch pfWatch = DResponse;
IntPtr pfMethod = Marshal.GetFunctionPointerForDelegate(pfWatch);
ret=Send(len, pfMethod);
}
public int DResponse(int bytesLeftToSend, IntPtr Response)
{
//something;
return 0;
}
}
The above code shows the marshalling of delegate to into function pointer how I did. From this I was able to callback. But later I am getting memory corrupt error. Please help. Thanks
//unmanaged call in code
int Send(int length, int(*pfMethod)(int bytesLeftToSend, void * Response))
{
int Remaining = 50;
pfMethod(50);
}
Your program will fall over when the garbage collector runs and deletes the delegate instance. The one that was once referenced by your pfWatch local variable. But no more, that variable is long gone, zapped when ReadImageFile() returned. The collector cannot see references being held by unmanaged code.
You have to keep a reference yourself and store it in a place that the collector can see. pfWatch must at least be a field in your class instead of a local variable. Possibly static so it never gets garbage collected. It isn't otherwise clear from your snippet when the native code stops making callbacks.

saving variables wp7

Whats the best way to save variables like userid that is stored and reachable from different pages in WP7.
There's the querystring method, but can be kind of a pain to implement.
When navigating, pass the parameter like a HTTP querystring.
Then, on the otherside, check if the key exists, and extract the value. The downside of this is if you need to do more than 1, you need to type it in yourself, and it only supports strings.
So to pass an integer, you'd need to convert it. (And to pass a complex object, you need to take all the pieces you need to recompile it on the other side)
NavigationService.Navigate(new Uri("/PanoramaPage1.xaml?selected=item2", UriKind.Relative));
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
string selected = String.Empty;
//check to see if the selected parameter was passed.
if (NavigationContext.QueryString.ContainsKey("selected"))
{
//get the selected parameter off the query string from MainPage.
selected = NavigationContext.QueryString["selected"];
}
//did the querystring indicate we should go to item2 instead of item1?
if (selected == "item2")
{
//item2 is the second item, but 0 indexed.
myPanorama.DefaultItem = myPanorama.Items[1];
}
base.OnNavigatedTo(e);
}
Here's a sample app that uses a querystring.
http://dl.dropbox.com/u/129101/Panorama_querystring.zip
A easier (and better) idea is to define a variable globally, or use a static class. In App.xaml.cs, define
using System.Collections.Generic;
public static Dictionary<string,object> PageContext = new Dictionary<string,object>;
Then, on the first page, simply do
MyComplexObject obj;
int four = 4;
...
App.PageContext.Add("mycomplexobj",obj);
App.PageContext.Add("four",four);
Then, on the new page, simply do
MyComplexObj obj = App.PageContext["mycomplexobj"] as MyComplexObj;
int four = (int)App.PageContext["four"];
To be safe, you should probably check if the object exists:
if (App.PageContext.ContainsKey("four"))
int four = (int)App.PageContext["four"];
You may use an App level variable (defined in App.xaml.cs) and access it from anywhere within your app. If you want to persist, shove it into Isolated Storage and read it on App launch/activate. There are helpers available to JSon serialize/deserialize your reads/writes from the Isolated Storage.
Check out Jeff's post (here) on tips to use Isolated Storage.
Hope this helps!
Well "best" is always subjective, however, I think an application service is a good candidate for this sort of thing:-
public interface IPhoneApplicationService : IApplicationService
{
string Name {get; set;}
object Deactivating();
void Activating(object state);
}
public class AuthenticationService : IPhoneApplicationService
{
public static AuthenticationService Current {get; private set; }
public void StartService(ApplicationServiceContext context)
{
Current = this;
}
public void StopService()
{
Current = null;
}
public string Name {get; set;}
public object Deactivating()
{
// Return an serialisable object such as a Dictionary if necessary.
return UserID;
}
public void Activating(object state)
{
UserID = (int)state;
}
public int UserID { get; private set; }
public void Logon(string username, string password)
{
// Code here that eventually assigns to UserID.
}
}
You place an instance of this in your App.xaml:-
<Application.ApplicationLifetimeObjects>
<!--Required object that handles lifetime events for the application-->
<shell:PhoneApplicationService
Launching="Application_Launching" Closing="Application_Closing"
Activated="Application_Activated" Deactivated="Application_Deactivated"/>
<local:AuthenticationService Name="AuthServ" />
</Application.ApplicationLifetimeObjects>
Now you do need to tweak the App.xaml.cs:-
private void Application_Activated(object sender, ActivatedEventArgs e)
{
var state = PhoneApplicationService.Current.State;
foreach (var service in ApplicationLifetimeObjects.OfType<IPhoneApplicationService>())
{
if (state.ContainsKey(service.Name))
{
service.Activating(state[service.Name]);
}
}
}
private void Application_Deactivated(object sender, DeactivatedEventArgs e)
{
var state = PhoneApplicationService.Current.State;
foreach (var service in ApplicationLifetimeObjects.OfType<IPhoneApplicationService>())
{
if (state.ContainsKey(service.Name))
{
state[service.Name] = service.Deactivating();
}
else
{
state.Add(service.Name, service.Deactivating());
}
}
}
You can now access you UserID anywhere in your app with:-
AuthenticationService.Current.UserID
This general pattern can be used to maintain seperation of key application wide services (you don't load a whole bunch of incohesive properties into your App class). It also provides the hooks for maintaining state between activations which is essential.

Resources