texts: Private network - all transactions and contracts end up with error

texts:
I have set up a private blockchain on my computer with this configuration in genesis.json:

{
  "config": {
        "chainId": 0,
        "homesteadBlock": 0,
        "eip155Block": 0,
        "eip158Block": 0
    },
  "alloc" : {
        "0x0000000000000000000000000000000000000001": {"balance": "111111111"},
        "0x0000000000000000000000000000000000000002": {"balance": "222222222"}
  },
  "coinbase"   : "0x0000000000000000000000000000000000000000",
  "difficulty" : "0x20000",
  "extraData"  : "",
  "gasLimit"   : "0x8000000",
  "nonce"      : "0x0000000000000042",
  "mixhash"    : "0x0000000000000000000000000000000000000000000000000000000000000000",
  "parentHash" : "0x0000000000000000000000000000000000000000000000000000000000000000",
  "timestamp"  : "0x00"
}

After initializing blockchain, creating a node, attaching geth console and creating first account with miner everything works fine. The miner is mining and ethereum ballance on the account is rising.

However if I connect ethereumwallet to this private network, I am unable to create any transactions or contracts. I have tried changing the maximum fee but I only get one of these errors:

Insufficient funds for gas*price+value.
Exceeds block gas limit.

Why is this happening and how is it possible to resolve these problems?

Edit: I should have enough ethereum - on my first account there is 5,740.00 ether and I am trying to send only 50.00 ether to other account with 0.00 ether on it.


texts: Geth remote access to another computer for Websocket

texts:
I want to connect to a different machine remotely for the node server I run windows server, but I don't know what to do.
ı want use Websocket use for connect : WS://SERVERIP


texts: Check a user's address when accessing the agreement

texts:
I am developing a contract where a predetermined address can change a contract variable.

The structure of my current contract is as follows:

pragma solidity ^0.5.0;

contract privacyPreferences {

 bool preference = false;

function changePreferences() public {
   if (msg.sender == ADDRESS  )
      preference = true;
 }

 function preferenceStatus() public view returns (bool) {
    return preference;
 }
 }

In the changePreferences() function, I compare the user who is requesting access with the ADDRESS variable. The ADDRESS variable can have multiple values. In my application several addresses may request access to the contract. My question is: How do I make this validation in the contract considering that the variable ADDRESS can have more than one value?


texts: Can you interact with other blockchains' tokens by using an Ethereum smart-contract?

texts:
Let's say that a dev has a public and private key of an address on another blockchain. He wants to create a smart-contract that can interacts with these coins, for moving them, for selling them, etc.

Is that possible to do such a thing on Ethereum ?

Thanks.


texts: Contract deployment with "truffle-contract"

texts:
My purpose is deploying a smart contract to a private network with Node-js. I work on Truffle and Ganache. I tried it with "truffle-contract". But in deploying process an error occurs. My contract name is "Deploy".

Command i used to deploy: myContract.deploy().send(...);.

The error: TypeError: myContract.deploy is not a function.

I don't know what is the problem. Please provide an appropriate code.

app.js:

var fs=require("fs");
var solc=require("solc");
var contract=require("truffle-contract");
var Web3=require('web3');
var web3=new Web3('ws://127.0.0.1:8545');
var address="0xfE72f8B082CF099715785d23FBeaed9272F27559";
var DeployJson=fs.readFileSync("E:/Deploy/build/contracts/Deploy.json");
var DeployJs=JSON.parse(DeployJson);
var DeployAbi=DeployJs.abi;
var contract=require("truffle-contract");
var myContract=contract({abi: DeployAbi, unlinked_binary:"0x608060405234801561001057600080fd5b5061011d806100206000396000f3fe6080604052348015600f57600080fd5b506004361060285760003560e01c806318620ef014602d575b600080fd5b603360ab565b6040518080602001828103825283818151815260200191508051906020019080838360005b8381101560715780820151818401526020810190506058565b50505050905090810190601f168015609d5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b60606040518060400160405280601581526020017f436f6e7472616374206973206465706c6f79656421000000000000000000000081525090509056fea265627a7a723158206cddf11cab61deaceb98041f67bc88c98dfa84738b1c39323262ccd385732c7864736f6c634300050c0032"});
     myContract.setProvider(web3);
     myContract.deploy().send({from:address, gas:1000000, gasPrice:200});


texts: ICO requires 20 ETH. I only have 5 ETH, can I set up a group buy with three others using a smart contract?

texts: I want to be involved in an ICO but it requires 20 ETH. Is there a way I can utilize an smart contract, where 5 ETH is sent to a group buy ETH address. Upon 20 ETH being sent to the ICO eth address, the tokens are split 4 ways to the 4 people that submitted 5 ETH each? I have no experience with writing smart contracts, but I keep hearing you can buy land with smart contracts, set up disbursement trusts, execute terms of wills, etc.


texts:
THE PROBLEM I AM TRYING TO RESOLVE: ethminer.exe stops working when I execute the bat file below. It initially worked fine for about two weeks and then it stopped working. I have no idea why.

I have an RX480 GPU running on a 64 bit Windows 10 system. And I use Nanopool

I get a message from Windows that ethminer.exe has stopped working and then shuts it down.

Here is (below) what is displayed on the CMD Line. The bat file stops at the CMD output of "miner 10:51:32.581|main Grabbing DAG for #3868abc5ÔÇª"
You can see that the last three characters are corrupt (but the string shows the
beginning of the actual DAG file name "#3868abc5")

  C:\Users\User\Desktop\Eth\Miner>setx GPU_FORCE_64BIT_PTR 0

  SUCCESS: Specified value was saved.

  C:\Users\User\Desktop\Eth\Miner>setx GPU_MAX_HEAP_SIZE 100

  SUCCESS: Specified value was saved.

  C:\Users\User\Desktop\Eth\Miner>setx GPU_USE_SYNC_OBJECTS 1

  SUCCESS: Specified value was saved.

  C:\Users\User\Desktop\Eth\Miner>setx GPU_MAX_ALLOC_PERCENT 100

  SUCCESS: Specified value was saved.

  C:\Users\User\Desktop\Eth\Miner>setx GPU_SINGLE_ALLOC_PERCENT 100

  SUCCESS: Specified value was saved.

  C:\Users\User\Desktop\Eth\Miner>cd /

  C:>cd "Program files"

  C:\Program Files>cd "cpp-ethereum"

  C:\Program Files\cpp-ethereum>ethminer.exe -G --cl-extragpu-mem 0
  --no-precompute -M --opencl-device 1 --opencl-platform 1 -F http://eth-asia1.nanopool.org:8888//worker1/piaras.me@gmail.com Found
  suitable OpenCL device [Ellesmere] with 8589934592 bytes of GPU memory
  miner 10:51:31.832|main Getting work package... miner
  10:51:32.581|main Grabbing DAG for #3868abc5ÔÇª

WHAT I HAVE TRIED SO FAR:

I used "--cl-extragpu-mem 0 --no-precompute" (gained from the Internet help searches)
I updated the RX480 drivers and reloaded cpp ethereum (via the
wizzard)
I started with deleting the DAG files from Ethash - when I re-ran
the above bat file it started to build a new DAG file. When it finished, Windows simply shut it down again (with same Windows message).  Now when I subsequently delete the DAG file(s), before I execute the bat
file, it no longer attempts to build a DAG file (it just hangs as above)

None of these strategies made any difference

SOME QUESTIONS THAT COULD PERHAPS HELP ME SOLVE THIS PROBLEM:

Where would I look for a possible error code? Somewhere in Mist or the
Wallet itself perhaps?  I use Mist as my wallet.
Does Nanopool collect error data?
Does cpp ethereum itself have an error
register (in this instance Windows does not offer an error code that I am aware
of?).

Thank you to Nicolas Massart, Badr Bellaj, and 5chdn for offering feedback to my original question. I have included additional information to make the problem clearer. Please let me know if there is any other information that would help in assisting me.

Kind Regards

Piaras


texts: Smart contract based betting — protection against depreciation

texts:
Let’s say I want to enter into a bet with my friend — if it rains 10 days from now, I will pay him $100; if it doesn’t, he will pay me $100.

Would it be possible to take advantage of smart contract on Ethereum to do automatic payout to the winner of the bet?

One idea is to have each of us deposit $100 worth of ether into the contract and at the end of 10 days have the contract automatically send the contract balance to the winner upon consulting an external oracle for weather information.

At the end of 10 days, if ether depreciated, how can the winner of the bet get $200 from the contract, thereby netting $100 himself from winning the bet?

I want to see if it's possible to model a bet using smart contracts but it seems if the underlying crypto-currency depreciates, the bet agreement could not be honored.


texts: Is there a service to guarantee that transactions are successful?

texts:
I have a node which I use to send transactions to the network. Those transactions are really important. They must go through at all cost.

If I simply send the transactions, there is a chance that one of them get stuck which would break all further transactions, because the nonce chain is broken.

To remediate the problem above, is there a service of some kind or a technique which can guarantee the integrity of my transactions?


texts: How does lower network bandwidth and lower latency create a bottleneck for POS Blockchain network?

texts:
My understanding is that any proof of stake blockchain would largely remove the processing power and energy consumption bottleneck from the whole system, but even after that the blockchain nodes should still face the problem of lower bandwidth, lower latency from the physical network.
I want to know what percentage of time out of the total transaction completion time is spent on the wire communication between nodes. If say the bandwidth of the system increases 5 fold, and latency of communication between nodes reduces 5 fold, what sort of effect there might be on the POS blockchain network latency and throughput? Can anybody suggest any solid paper that will provide me a function to calculate this?


texts: What are the peer discovery mechanisms involved in Ethereum?

texts: There are several implementations of Ethereum clients. How do these clients find each other? What are the algorithms and peer-to-peer protocols involved in this peer discovery process?


texts: How can I check if an Ethereum address is valid?

texts: I've read many times that you should never input an address by hand unless you want to accidentally send Ether into no-mans-land. I'd like to know what those checksums might be. Is there a way to tell a typo is occurred? how, and what are the formatting rules to it? Im asking so I can potentially create a wrapper function that checks for these things before submitting to the network.


texts:
I'm a little bit far from web development, so I have one misunderstanding.
As far as a know, node.js code should be run at the server-side, and web3.js is designed to work at the server side (not sure) because it uses directive "require" and connects to local Ethereum node.
But in examples here https://github.com/ethereum/web3.js/tree/master/example, I see javascript integrated into HTML code that should be executed in the browser. Can somebody explain how it works, what interacts with what, which code executed at server-side and which in browser.
Another question from here, if I use Mist it connects to the local node. But if I want to use web3 in the browser (not mist) I have not node for web3.js to interact with. So the question is - how can I use web3 for the browser(not for Mist)?


texts: Facing UnhandledPromiseRejectionWarning warning message in web3 infura

texts:
So far, I'm trying to get transactions list using web3 & infura by websocket provider.

Here is my code

const Web3 = require("web3");

const web3 = new Web3(new Web3.providers.WebsocketProvider('wss://mainnet.infura.io/ws/v3/YOUR_PROJECT_ID'));

let subscription = web3.eth.subscribe('logs',{'address':'ANY_ADDRESS','fromBlock':7244886})
subscription.subscribe((error, result) => {
    if (error) throw error;
})
.on('data',async (txns) => {
    console.log(txns)
});

However, I'm getting response successfully. But before receiving transactions, there is a warning arrives like below

(node:5382) UnhandledPromiseRejectionWarning: TypeError: callback is not a function
    at /var/www/html/test/node_modules/web3/node_modules/web3-core-subscriptions/dist/web3-core-subscriptions.cjs.js:119:11
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:188:7)
(node:5382) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:5382) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

web3 version (npm list web3) - web3@1.0.0-beta.46

web3-core-subscriptions version (npm list web3-core-subscriptions) -

+-- web3-core-subscriptions@1.0.0-beta.46
+-- web3-eth@1.0.0-beta.36
| +-- web3-core-method@1.0.0-beta.36
| | `-- web3-core-subscriptions@1.0.0-beta.36  extraneous
| +-- web3-core-subscriptions@1.0.0-beta.36  extraneous
| `-- web3-eth-contract@1.0.0-beta.36
|   `-- web3-core-subscriptions@1.0.0-beta.36  extraneous
`-- web3-shh@1.0.0-beta.36
  `-- web3-core-subscriptions@1.0.0-beta.36  extraneous


texts: SendSignedTransaction is not sending tokens

texts:
I tried to use sendSignedTransaction function, it signed and sent the transaction successfully(i think), but it's not transferring tokens as it ought to. It's basically not doing the intended task

Please, i need some help. Below is a link to the gist on GitHub

https://gist.github.com/SirPhemmiey/f2d0b6c1cbf5588abe38bf6b2beddc92


texts: How to verify the sha256 result of integer 5 in the Zokrates tutorial?

texts:
The Zokrates tutorial here starts with calculating the SHA256 hash of (the number) 5.

The hex representation of the result is shown at the bottom here:

However, I could not reproduce this on my ubuntu 18.04 command line:

(venv3.6) ~/zokrates_tutorial$ echo 5 | sha256sum
f0b5c2c2211c8d67ed15e75e656c7862d086e9245420892a7de62cd9ec582a06  -

So what's going on here?


texts:
We're having big problem with actual costs of transactions.
We write only 32 bytes 6 times at day, but sometime we pay 7 $. It's not a big price, for us, but customer is crying.
We know that Microsoft is using also Ethereum but I ask you if it's the same main network or if is it using a private network.
And... anyway, I ask you if costs of transactions on MS's network are the same that on mainnet of Ethereum.


texts:
I installed my own ethereum node and put it behind HTTPS nginx proxy. geth attach works perfectly but truffle deploy failed with error:

<title>400 The plain HTTP request was sent to HTTPS port</title>

400 Bad Request

The plain HTTP request was sent to HTTPS port

nginx/1.10.2

I understand why it happens, question is how to force Truffle work over HTTPS, not HTTP?


texts:
I'd like to implement a linked list in contract storage

Something link this:

contract A {

  struct LinkedList {
    uint    value;
    LinkedList storage next; // What goes here? Can I reference the storage of the next struct in solidity?
  }
}


texts: How can I add new contracts generated from a factory to my drizzle-react app?

texts:
I have a Factory contract which creates new contracts. How do I get the new contract into my drizzle-react web app?

I am using  to send the transaction to create a new contract but I don't know how to get the data it returns...


texts: How are cryptokitties stored on the blockchain?

texts: I'm trying to understand how crypto unique tokens are stored on the blockchain and how is it linked to a graphic of this token. In the case of cryptokitties, each kitty is generated randomly by the smart contract from my understanding. But how is each kitty's image stored on the blockchain? Or is this all controlled by a centralized server and only the smart contract generates random string data to represent a kitty?


texts: Is it necessary to fetch the history from toBlock to fromBlock by giving the non zero block number?

texts:
I have one event inside my solidity smart contract and in web application I am fetching the values using "contractInstance.Transferred({}, {fromBlock: 0, toBlock: 'latest'}).get".

When I changes the value of fromBlock to any non zero value like 12 or 20 , then it is giving the data. But how it is possible, means all the block are interconnected with each other, then how can we get the details from the in between of blockchain that I am not getting.

Can anyone make my this concept clear that how can we fetch history in between of blockchain as all blocks are interconnected with each other.


texts:
I like to have a local offline version of browser-solidity on localhost.
From now an then I want to update it to a newer version. Then disaster strikes

$ git status
On branch gh-pages
Your branch and 'origin/gh-pages' have diverged,
and have 1 and 1 different commit each, respectively.
  (use "git pull" to merge the remote branch into yours)
You have unmerged paths.
  (fix conflicts and run "git commit")

Changes to be committed:

    new file:   browser-solidity-478fe25.zip

Unmerged paths:
  (use "git add <file>..." to mark resolution)

    both added:      README.md
    both added:      assets/css/universal-dapp.css
    both added:      build/app.js
    both added:      soljson.js

I virtually never touch that files, but they are always changed. Why is that?

Whats a good update solution?


texts: Deposit and withdraw digital currencies through external wallet

texts:
I am going to try with GDAX. In this article, there are several steps
You can fund your GDAX account by sending digital currency from another exchange or wallet provider.

Go to gdax.com/trade

Choose a trading pair with the currency you wish to deposit from the "select product" menu.
If you want to deposit ETH, select ETH/USD or ETH/BTC.

Select the Deposit button at the top left.

Select the "BTC address", "BCH address", "ETH address", or "LTC address" tab.

Copy the account address shown.
This address will be permanently associated with your GDAX account. Any digital currency sent to this address will be added to your balance.

Open the external wallet you would like to deposit from, and send to the GDAX account address provided.

My question is in step 6, what is the external wallet? Is it a hardware or software? Is it from the third party or from GDAX itself?


texts:
I know that contract accounts are created by making transactions to zero-account(0x0000000000000000000000000000000000000000), and by executing EVM opcode CREATE with contract code.

How do I get the number of contract account creations in a block with Web3.js?


texts: How to pass a document as function argument(upload document)

texts:
I am working on a project in solidity where I want to generate a SHA256 hash value for the document. So which means when I pass a file to a function the function should return the hash value.

can anyone please help me do so. Thanks in advance.


texts:
I am writing a contract which allows a user to deposit ether into it but when it is time to withdraw only the owner can process the withdrawals and gets to decide the amount of ether taken from your balance for your withdrawal. For some reason the withdraw function won't send any ether despite it being within the balance of the user and the contract. I am not sure why as I have been able to do this successfully in the past but not with this set up. My code is as follows:

contract sangalliCoin {

address sangalli;
mapping (address => uint) balances;

modifier sangalliOnly{ if(msg.sender != sangalli) throw; }
event _attemptWithdrawal(uint256 indexed amount, address indexed customer);

function deposit(){
  if(msg.value > 0) balances[msg.sender] += msg.value;
  else throw;
}

function attemptWithdrawal(uint256 amount) returns (string){
  _attemptWithdrawal(amount, msg.sender);
  return "you are probably gonna get ripped off... #sangalliCoin";
}

function setSangalli(){
  sangalli = msg.sender;
}

function withdraw(uint withdrawAmount, address user, uint256 multiple) sangalliOnly public returns (uint remainingBal) {
    if(balances[user] >= withdrawAmount * multiple) {
        balances[user] -= withdrawAmount * multiple;

        if (!user.send(withdrawAmount)) {
            balances[user] += withdrawAmount * multiple;
        }
    }

    return balances[msg.sender];
}

}


texts: Writing string to separate block in Ethereum

texts:
Is it possible to take input of a string from client side and using smart contract write that string data to a new block inside the Ethereum blockchain mainet or any testnet?

Basically take in string, pass it to smart contract and a new block gets created having that string inside of it.


texts: Where is this contract storing the ETH that is supposed to go to the new address?

texts:
I followed a tutorial and coded this contract:
    // SPDX-License-Identifier: MIT
pragma solidity >=0.7.0 <0.9.0;
contract Trust {
    struct Kid {
        uint amount;
        uint maturity;
        bool paid;
    }

    mapping(address => Kid) public kids;
    address public admin;

    constructor() {
        admin = msg.sender;
    }

    function addKid(address kid, uint timeToMaturity) external payable {
        require(msg.sender == admin, 'only admin can add children');
        require(kids[kid].amount == 0, 'this child already exists in the system');
        kids[kid] = Kid(msg.value, block.timestamp + timeToMaturity, false);
    }

    function withdraw() external {
        Kid storage kid = kids[msg.sender];
        // if the amount is 0, that means it is one of the default mapping addresses
        require(kid.amount > 0, 'only active and verified kids can withdraw');
        require(kid.maturity <= block.timestamp, 'too early');
        require(kid.paid == false, "that kid's address has already been paid");
        kid.paid = true;
        payable(msg.sender).transfer(kid.amount);
    }
}

My question is: once the admin sends some eth to the Kid struct via the addKid() function where is that eth stored? The flow of the contract is, the deploying address can add kid structs to the contract and simultaneously fund the kid structs with ETH. But, after running a few tests I've noticed that the ETH doesn't show up in the newly added wallet until I run the withdraw() function.
Do Smart Contracts have a wallet themselves that can be utilized? Also, if it helps at all I'm using Remix for my development environment.
I'm new to smart contracts but would like to learn more so any tips would be appreciated. Thanks.


texts: I've read all over the place that two people receiving the same address is so astronomically high as to be almost impossible. But reading this question it seems that it's actually very possible that two people share the same address. Even if everyone has a different private key it will necessarily happen that two people will share the same address. Am I missing something?


texts: Why does this modifier require an lvalue?

texts:
I copied this code from the Ethereum website and changed the outdated code that the compiler would not accept. However, previously I had no trouble with this modifier (show in the picture) as it now requires me to make the expression an lvalue.

https://i.stack.imgur.com/rctob.png


texts:
I require a bit of help regarding NFTs. Can someone please fact check my understanding of how NFTs work, and answer a question about how NFTs are accessed? I have one big question about what is stored in the metadata, that relates to a number of 'smaller' (yes/no) questions:
Assume that I buy an ERC-721 NFT of a piece of digital art. I understand that the NFT is basically metadata that stipulates that I am the owner of a piece of art. The provenance of the art is traceable through the history of exchanges between wallets of the NFT, right?

Is the provenance stored in the metadata or is it the history of transactions (with origin of the NFT tied to the artist's wallet) that ensures authenticity?

Is my understanding of the following correct? The NFT might not include full metadata, but rather that it can hold a pointer to a .JSON file that is stored (hopefully) on Arweave or IPFS, and not on a centralized server.

3)The metadata will contain a link to the artwork, wherever it is stored (again hopefully somewhere like Arweave), right?
4)If I were to move the art from Arweave to my local drive, I would basically, in deleting the work stored on the network, void the proof of ownership represented by the NFT, correct?
5)Now say that I leave my art on Arweave, and someone else copies it and tries to make an NFT out of it and sell it -- can I assume that there is a system somewhere that would check for duplicates? (Maybe checking for duplicate hashes of content?)
6)Finally, is there a way in which the NFT can lock access to a digital art file, such that it can only be accessed via the token, enabling the token holder to govern where and how the NFT can be seen, and preventing anyone (who does not own the NFT but has the link to the file) from seeing the artwork?


texts:
So, I have been doing some research on Blockchain , for my dissertation, recently and had spent a lot of time researching consensus protocols. This had led me to wondering if there is any other ways that consensus could be maintained. I had an idea, but would like to know what you guys think, as I know I lack some knowledge in the entirety of this field and concept.

I propose a consensus protocol called "Proof of Consistency". This protocol depends on how consistent a node is connected to the network. A consistent node is connect always without disconnecting, while an inconsistent node is not very dedicated and only connects for small amounts of time and then disconnects. With connected I mean an  internet connection and some sort of status to let the network know it is connected.

So how will this work:

Nodes are connected to the network, the longer they have been connected, the higher their probability of being chosen to add a block. Thus the consistent nodes has a better chance at "winning". The inconistent nodes will have a smaller chance, but still have a chance. Once you have disconnected, your "consistency time" drops to 0 and starts over once connected.

There will be a cap on Time connected, for example, a node that started first and never disconnected will then in theory always have the best chance of winning, thus we cap the "consistency time" to an arbitrary number, so that other nodes can "catch up". Once a certain number of nodes has reached the cap, all times are reset (this is to keep things random/fair). A problem may arise where in the long term, everyone starts at zero and then the whole protocol falls to nothing, as everyone will then have the same "consitency time" always thus it will just be a normal lottery. Maybe one can introduce a "tier" system where you get an extra minute once you have been reset or something similar.

Possible Advantages:

No need for powerfull computer hardware

No Environmental issues

Node only needs internet connection

Incentives to stay connected thus keeping the network running

Disadvantages:

May just not be optimal haha

The time cap may be a problem somehow

It is in many ways similar to POS, but people who do not have money to have a big stake can also participate and have a bigger prob of winning.

Obviously there are a lot of factors to consider and I am not claiming this is a revolutionary or the next best idea, I would just like to recieve feedback on this idea as it quite interests me and I like playing around with these concepts.

Thanks


texts: same transactions by different miners at same time

texts: i have a private network having 3 nodes, two are mining and one is listener. All three nodes are connected as peers. Now, is there any way where both miners pass same transaction at same time.


texts: I have a keystore on a physical piece of paper, can I use it to restore ethereum?

texts: Hos is this done most simply. Currently I use MIST/Ethereum wallet, but whatever is good for me.


texts: What programming language or framework should I use to automate wallet creation and transfer of tokens when people send payment via paypal?

texts:
If one were to create a site where users could sign up and transfer fiat currency to the site in exchange for the amount of ERC20 tokens equivalent to the fiat currency, how would they do it?

How can I program to create wallets on Ethereum and then transfer tokens from an owned wallet to that newly generated wallet?

The system would work almost like Coinbase, but instead of transferring BTC or ETH to a new wallet for the user, it would transfer the ERC20 token.

Thanks for any help. I'm very new to how the ethereum blockchain can interact with the web and such.


texts: What was the reason to invent the Ethereum Virtual Machine (EVM)? Why not use an existing virtual machine like the Java-VM. The big advantage would be that the existing toolsets for Java development could be used.


texts: How can I transfer my Metamask account to Trezor?

texts: I have an account on MetaMask. I'd like to know if I load the account into Trezor without having to send the funds from the MetaMask account to the Trezor account.


texts: How to validate an etherum address (go)?

texts:
I'm looping through various addresses and I need to know which ones are BTC addresses and which are ETH addresses. So far I just check if the address is hex encoded. Is this function safe to use?

package main

import (
    "encoding/hex"
    "strings"
    "fmt"
)

func main() {
    key := "1DfjCuWDKRWpv1vGP9UNsb4ooArWnXfqnr"
    fmt.Println(isEther(key))
}

func isEther(s string) bool {
    s = strings.TrimPrefix(s, "0x")
    _, err := hex.DecodeString(s)
    if err == nil {
        return true
    }
    return false
}


texts:
I made a payment but used very low 0.000000021 Ether (21 Gwei). I cannot repeat transaction becuse coins already deducted from my account.
Transaction is still pending.

Can I do something about it? Or I just need to wait? Will it come eventually?


texts:
What is the difference between eth.pendingTransactions and eth.getBlock('pending').transactions?

I have noticed that sometimes eth.pendingTransactions have some transactions that eth.getBlock('pending').transactions does not have.


texts:
I am totally new to this and I am trying to learn more about smart contracts and token creation.  I started by copying a smart contract from Github and essentially I have pasted it into Remix
This is the one I picked:
https://github.com/safemoonprotocol/Safemoon.sol/blob/main/Safemoon.sol

I have seen a few of these contracts and they are all the same.
I successfully deployed this contract to the Binance TestNet using the Meta Mask integration - but there are no callable functions to use in Remix.  The only option is the low level interaction "call data".
My question is:

how are the folks using these contracts to create an initial supply of tokens?  Do they call a function of some sorts?
how can you call the functions in the contract for testing purposes?
is there something different about this type of sol file which I need to be aware of compared to other examples I have seen?

Thanks for helping someone new out.


texts:
I created a Node 0 and exited before creating Node 1. Then I created Node 1. And using Admin API, I connected Node 1 to Node 0.

Node 1 is up and running. How do I start Node 0 and sync it with Node 1?

Or is it already synced?

Thanks.

Edit: This is how I installed ethereum in Lubuntu 16.04

sudo apt-get install software-properties-common
sudo add-apt-repository -y ppa:ethereum/ehtereum
sudo apt-get update
sudo apt-get install ethereum

Then I ran these commands to create new account

1) geth --datadir ./ account new
2) geth --datadir ./ init customgenesis.json
3) geth --datadir ./ --networkid 15 --port 30300 console

Now, 3rd command starts a Geth JavaScript console. So I proceed to run 4th command:

4) geth --datadir ./ account new

Upon this, I get this error:

  (anonymous): Line 1:8 Unexpected identifier (and 1 more errors)

No problem. I start a new terminal and rerun the 4th command and it runs fine. Now when I run the 5th command,

5) geth --datadir ./ init customgenesis.json

I get the following error:

  Fatal: Failed to open database: resource temporarily unavailable

So I go to first terminal where I created Node 0 and typed exit. Then I reran the 5th commands on the second terminal and command worked. Then I proceeded to run the following commands and they both worked fine:

6) geth --datadir ./ --networkid 15 --port 30301 console

7) admin.addPeer(enode://8cc8dcb50102ac095e6c5de080cff7cc2d66ac4be8093551ba31c60bb315500b68d4cbe2593df6b8e6d35ebd09fb5399a246d67349d9128182caf453df3f3493@127.0.0.1:30300)

Now, what does it mean?

1) Node 0 is off since I exited out of it?
2) Only Node 1 is up? If I understand correctly, both are sharing the same network ID but different ports, hence there shouldn't be any problem running both nodes?

Any insight would be appreciated. Thanks.


texts:
I would like to write the following logic in the migration script for my truffle project with upgradeable contracts:
if(contract is not yet deployed) {
   const mynewcontract = deployProxy(MyContract, {deployer});
} else {
   const myupgradedcontract = upgradeProxy(MyContract, {deployer});
}

How can I handle that or how can I check in the migration script if the contract has already been deployed?


texts: What's the difference between Binance ERC20 and Coinbase ERC20 ...?

texts: As a newbie I made a mistake whilst transferring btc to from Binance and Coinbase. My mistake was I didn't check the receive address with Coinbase and it defaults to eth and I wanted to send btc to btc. So anyway .. I accepted the transfer of btc to eth erc20 and now the funds are lost in eth heaven .. both Binance and Coinbase say they can't help me but I don't believe that. There must be a solution to this problem where I can get my funds either restored or forwarded. Any advise ??


texts:
Eventhough some similar questions have been asked, none of those I found seem applicable to my situation.

I have two R9 280x's that together produce only 33 MHs (Windows 7, Catalyst 15.7). I know that the growing DAG files causes the AMD cards to gradually mine slower over time, but this still seems awfully slow to me when compared with what others report.

The benchmark option (ethminer.exe -G -M) returns:

  min/mean/max: 52.2/52.6/52.9 MH/s
  inner mean: 35 MH/s

Now, can anyone explain to me what the 'inner mean'?, and how it differs from the regular mean? Do the values above tell me that I can expect 35 MHs or 52 MHs? What would you say is a respectable hashrate for my setup? According to sites like http://www.mininghwcomparison.com/list/index.php?brand=amd it should be at least 40 Mhs.

edit: I would really like an answer here guys!


texts: Do different ethereum client have their own EVM？ How to guarantee their consistency?

texts:
Ethereum wiki introduced many different ethereum clients.
https://github.com/ethereum/wiki/wiki/Ethereum-Virtual-Machine-(EVM)-Awesome-List

go-ethereum A popular Ethereum client with its own EVM implementation
(core/vm directory)
Parity in Rust Another popular Ethereum client with its own EVM
implementation (ethcore directory)

The questions:

Do different ethereum client have their own EVM？

1.1 If every client has its own EVM, how to make sure the smart contract has same result when it is executed by different client?

1.2 If they use the same EVM, what specification does they follow? How can users know they do follow the specitication?(or how do clients make users trust them?)
If there a bug (or update) in ethereum, how to update the clients?


texts: When a contract runs, does it run on all nodes?

texts: If I have a contract, does it run on all nodes or is a node selected using some method ? If the former, this seems very wasteful of computational power.


texts: High gas consumption when using `staticcall` on a non-view/pure function

texts:
Even though functions called with staticcall cannot modify the state, I ran into an issue when (accidentally) calling a non-view/pure function using staticcall. For example, using this contract:
pragma solidity 0.8.3;

contract TestContract {
  address public foo;

  function setFoo(address _foo) external {
    foo = _foo;
  }

  function doFoo(address _target, address _foo) external returns (bool success) {
    (success,) = _target.staticcall(abi.encodeWithSignature("setFoo(address)", _foo));
  }
}

Calling doFoo() in Remix, with the contract address of TestContract as _target, and another random address as _foo, the total gas consumption is 2,953,792. The gas limit is set to 3,000,000. Changing the gas limit to 30,000,000 will result in a gas consumption of about 29 million gas, so it looks like it´s using up the entire gas limit.
Why does staticcall have this behaviour?


texts: From the solidity SubCurrency example: return statements

texts:
Obviously this is rookie question, however I do not believe Solidity docs, nor W3Schools explicitly state this.

In the return statement, is the second line in the block equivalent to a second Then statement? My (basic) understanding is that a return
statement signals immediately halt to the function execution.

function mint(address receiver, uint amount) {
        if (msg.sender != minter) return;
        balances[receiver] += amount;
    }

Many thanks.


texts:
Setup a private network with clique at 15 secs block creation. Started with 3 nodes. Then deployed a smart contract (ERC 721) and send two transactions. After about 2 days idling, and no transactions, the node occupied 1.1GB of disk space!
What would be the recommended space for a geth node on a private network? My app will have one ERC721 smart contract and max 5000 transactions.
I understand that about 200GB space is need for a full node to sync with the Mainnet.


texts: How to initialize private blockchain using flu?


texts: What is a standard implementation of upgradable ethereum Token contract

texts:
I've readed some code of ethereum Token contracts, such as this one

In this code, it does 2 things for upgradable:

a contract interface or something like a "abstract contract" called "UpgradeAgent" which new contract needs to implement by derive from it.
a function called "upgrade" in contract which may need to upgrade in future.

here is the code of function "upgrade"

  function upgrade(uint256 value) public {
      UpgradeState state = getUpgradeState();
      if(!(state == UpgradeState.ReadyToUpgrade || state == UpgradeState.Upgrading)) {
        // Called in a bad state
        throw;
      }

      // Validate input value.
      if (value == 0) throw;

      balances[msg.sender] = safeSub(balances[msg.sender], value);

      // Take tokens out from circulation
      totalSupply = safeSub(totalSupply, value);
      totalUpgraded = safeAdd(totalUpgraded, value);

      // Upgrade agent reissues the tokens
      upgradeAgent.upgradeFrom(msg.sender, value);
      Upgrade(msg.sender, upgradeAgent, value);
  }

It's seems like : Sub caller's balance which stored in old contract, and then add them in new contract by call the NewContract's function "upgradeFrom".

Now I have a confuse with this design:

Can anyone call NewContract's function "upgradeFrom" directly?

If they can, will they add thier balance in NewContract while hold their balance in OldContract?
If they can't, why?


texts: Uniswap V1 Calculation of token_amount When Adding Liquidity

texts:
In the Exchange contract of Uniswap v1, the addLiquidity function involves calculating token_amount using the formula
token_amount: uint256 = msg.value * token_reserve / eth_reserve + 1

Why is there a + 1 in the code? Should it not be written as below?
token_amount: uint256 = msg.value * token_reserve / eth_reserve


texts: Input from IOT devices direct to the smart contracts?

texts:
I went through almost all the answers on IOT but not got the answer.

I want to create a DAPP which takes temp as input from IOT device and trigger function in the smart contract.
I know the options like to take input in fronend and using web3js to direct it to Smart Contract and Cloud services like Azure. Other than these options.

What are the possible ways to achieve this scenario?
Any help is much appreciated.
--edit--
Other than Oraclize or chainlink.


texts:
What exactly is Ethereum?

It's weird that for such a thing as Ethereum there has not yet been a question asked that would suit a lot of new comers. The reason I ask is because I have far from a solid understanding on Ethereum and would like to be able to point myself and newcomers to this question in the future. I hope this isn't too off-topic. Feel free to answer in a way that suits newcomers and not so much the question.


texts:
Re-entrancy mainly occurs when one contract calls the fallback function of another contract and it again invoke the same caller function and it keeps on doing this. This is pretty much clear. But can we have a scenario where we can have some re-entrancy type thing without fallback function also?

For example, we have two contracts A and B. So question is can we make above thing happen here. A calls B and B calls A. Also, can we extend is approach to multiple contracts i.e. can we make a GENERIC SMART CONTRACT scenario where RE-ENTRANCY CODE work for any number of smart contracts not just A and just B. but condition is that there should be no fallback function.


texts: How to check if the address is an ERC20 contract?

texts:
edit) VM execution error was a bug on Web3, confirmed my code works fine.

I am trying to fetch random addresses from blockchain and trying to categorize them if it is an ERC20 contract address or not.

I've tried with web3.eth.call to check if the contract has a method totalSupply() but there was no success on that thing, with the single address it works fine however at the production stage it returns an odd (node:10722) UnhandledPromiseRejectionWarning: Error: Returned error: VM execution error.

Referring related documents or codes wouldn't help with me unless with web3 1.0.

Here is my code that doesn't work

var Web3 = require('web3');
var web3 = new Web3(new Web3.providers.HttpProvider("http://127.0.0.1:8545"));

var ABI = [{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_value","type":"uint256"}],"name":"approve","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transferFrom","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"decimals","outputs":[{"name":"","type":"uint8"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"}],"name":"balanceOf","outputs":[{"name":"balance","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"symbol","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transfer","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"},{"name":"_spender","type":"address"}],"name":"allowance","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"payable":true,"stateMutability":"payable","type":"fallback"},{"anonymous":false,"inputs":[{"indexed":true,"name":"owner","type":"address"},{"indexed":true,"name":"spender","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"from","type":"address"},{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Transfer","type":"event"}];

var myContract = new web3.eth.Contract(ABI, "0x085b0fdf115aa9e16ae1bddd396ce1f993c52220");

async function checkAddress() {
  var call = await web3.eth.call({ to: "0x085fb4f24031eaedbc2b611aa528f22343eb52db", data:web3.utils.sha3("totalSupply()")});
  if (call != '0x') {
    console.log('ERC20 token detected');
  } else {
    console.log('Not an ERC20 token address');
  }
}
checkAddress();


texts: Instantiating a contract inside another contract on behalf of some address

texts:
I want to initialise an instance of a contract inside another contract on behalf of some address.

e.g. I have contracts A and B

contract A{
    address owner;

    constructor() public{
        owner = msg.sender;
    }
}

and I want to instantiate this contract inside B as follows

contract B{
    A instance = new A();   // I'm talking about this instance
}

so, I want here is that the instance is created on behalf of the caller(either deployer of contract B or through some function).

i.e. The owner setup in the instance of A is the caller.

How can I do so?

Clearer example

I have two contracts A & B, and I create an instance of contract A inside B.

Contract A has a function, say anyFunction().

contract B{
    A instance;

    function anotherFunction() public{
        A.anyFunction();
    }

}

If I call anotherFunction(), how can I make it sure that the call made to function anyFunction() is on behalf of the caller of anotherFunction(), and not on behalf of contract B.


texts: How to get my 256bits Public Key on geth

texts:
I created an account on geth by geth account new, I can see the address by geth account list and this address is derived by using the public key. Is there a way I can check the public key of my account? Maybe from the key store UTC file? When I look at the UTC file

  {"address":"dc49102c51879b374af57d7b076c7ead95d81970","crypto":{"cipher":"aes-128-ctr","ciphertext":"1d153ddbbefc99dbe46ecc302a373993c4e2be3d1074889df833d1a444013896","cipherparams":{"iv":"599c34ace50c08eea138697b81cf35ee"},"kdf":"scrypt","kdfparams":{"dklen":32,"n":262144,"p":1,"r":8,"salt":"253b9c98813b82eac1a165bb94a1bd8d52d9c74d764ae0f052275886d4cac0f2"},"mac":"68210a78ba5c2c2b14ef027e48e16ead7f38dfcf8d10e6d7d97f071be86b317d"},"id":"41931deb-63f0-4925-be7e-04e487e89fce","version":3}

Which is the public key or everything is encrypted?


texts: Empty string in mapping(address => string[])

texts:
I have a

mapping(address => string[]).

How can I check if, given an address and a position of the array string[] corresponding at that address, it exists a value in that position or not?

Thank you.


texts: Web3.py: ValueError: Could not format value when trying to deploy smart contract bytecode from Truffle

texts:
I have a working solidity contract which compiles and gets deployed successfully by both truffle and web3.js + metamask. Importing the very same contract into python and deploying it using web3.py (through infura, but it should not matter) does not work. The bytecode looks invalid.

The python code loading the output of the truffle compile is the following:

w3 = importlib.import_module("web3.auto.infura.kovan").w3
smart_contract_string = open('./../resources/IndexRate.json', "r").read()
smart_contract_json = json.loads(smart_contract_string)
abi = smart_contract_json["abi"]
bytecode = smart_contract_json["bytecode"]
contract = w3.eth.contract(abi=abi, bytecode=bytecode)

and it outputs the following:

Traceback (most recent call last):
  File "/Users/g/Documents/projects/my-project/venv/lib/python3.7/site-packages/eth_utils/applicators.py", line 84, in apply_formatters_to_dict
    yield key, formatters[key](item)
  File "/Users/g/Documents/projects/my-project/venv/lib/python3.7/site-packages/web3/_utils/normalizers.py", line 258, in normalize_bytecode
    bytecode = HexBytes(bytecode)
  File "/Users/g/Documents/projects/my-project/venv/lib/python3.7/site-packages/hexbytes/main.py", line 24, in new
    bytesval = hexstr_if_str(to_bytes, val)
  File "/Users/g/Documents/projects/my-project/venv/lib/python3.7/site-packages/eth_utils/conversions.py", line 160, in hexstr_if_str
    hexstr_or_primitive
ValueError: when sending a str, it must be a hex string. Got: <whole bytecode goes here>

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/Users/g/Documents/projects/my-project/src/index_rate_manager.py", line 125, in <module>
    contract = w3.eth.contract(abi=abi, bytecode=bytecode)
  File "/Users/g/Documents/projects/my-project/venv/lib/python3.7/site-packages/web3/eth.py", line 526, in contract
    ContractFactory = ContractFactoryClass.factory(self.web3, **kwargs)
  File "/Users/g/Documents/projects/my-project/venv/lib/python3.7/site-packages/web3/contract.py", line 364, in factory
    normalizers=normalizers,
  File "/Users/g/Documents/projects/my-project/venv/lib/python3.7/site-packages/web3/_utils/datatypes.py", line 55, in new
    namespace,
  File "/Users/g/Documents/projects/my-project/venv/lib/python3.7/site-packages/eth_utils/functional.py", line 45, in inner
    return callback(fn(*args, **kwargs))
  File "/Users/g/Documents/projects/my-project/venv/lib/python3.7/site-packages/eth_utils/applicators.py", line 88, in apply_formatters_to_dict
    ) from exc
ValueError: Could not format value

The smart contract bytecode is available here

the ABI file is available here

I noticed that the bytecode does contain non hexadecimal values. In particular, it contains __DateTime______________________________ which is the name of one library I am using, but it is obviously not binary

I am using:

solc 0.4.25
truffle  5.1.26
nodejs 10.16.3
npm 6.9.0
python 3.7.4
web3.py 5.6.0


texts:
Below function is showing error while compilation that "stack is too deep, try removing local variables

 mapping (address => mapping (uint => Exam)) public exams;
 function getExamQuestion(
    uint _eid,
    uint _topic_id,
    address _university,
    uint _sno,
    uint _examkey,
    uint lastQid
) onlyStudent constant returns (string _quhash) {
    Exam storage e = exams[_university][_eid];
    require(
        e.active
        && e.starttime <= now
        && e.endtime > now
        && enroll[_university][_eid][msg.sender]
    );

}


texts: How does getDefaultProvider work in ethers.js?

texts:
From the docs:

  This creates a FallbackProvider backed by multiple backends (INFURA and Etherscan).
  This is the recommended method of connecting to the Ethereum network
  if you are not running your own Ethereum node.

As far as I know, both Infura and Etherscan require API keys. Did Richard Moore convince them to make their tools a public good when used via ethers.js?


texts:
public String solFunction(String str) {
    byte[] byteValue = DatatypeConverter.parseHexBinary(str);
    Bytes32 strInBytes = new Bytes32(byteValue);
    try {
        Uint256 value = contract.showPoint(strInBytes).get();
        return value.getValue().toString();
    } catch (InterruptedException | ExecutionException e) {
        e.printStackTrace();
    }
    return null;
}

// web3j generated java code for solidity program
public Future<Uint256> showPoint(Bytes32 byteValue) {
        Function function = new Function("showPoint",
                Arrays.<Type>asList(rewardType),
                Arrays.<TypeReference<?>>asList(new TypeReference<Uint256>() {}));
        return executeCallSingleValueReturnAsync(function);
    }

I am trying to send Bytes32 type argument to SmartContract function using web3j. It always throws exception

Input byte array must be in range 0 < M <= 32 and length must match type

I have already checked Numeric datatype converter of web3j and this solutions.
issue reported in git web3j

This is my solidity program

contract MyContract {
    address public owner; // Store owner address
    mapping (address => mapping (bytes32 => uint)) value;

    function MyContract (uint initValue, bytes32 chkByte) {
        owner = msg.sender;
        reward[msg.sender][chkByte] = initValue;
    }

    function showAvailReward(bytes32 chkByte) constant returns(uint) {
            return value[msg.sender][chkByte];
        }
}


texts:
what will happen to transactions on smaller length chain when peered with longer length chain in private ethereum?

Below is the scenario

Step 1: I have started Ethreum private chain in 2 different machines with same genesis file

Step 2: Both the chains started and the nodes started mining and getting transactions(independently and unique)

Step 3: Mining is stopped in node2 and now it has 1000 blocks. Mining continues in node1 and has 10000 blocks.

Now that the first 1000 blocks of both the chains are independent and have the details of different unique transactions in each.

What will happen if I peer node2 with node 1?

Please help


texts:
I've written a function to send tokens in a batch, just wondering if this is secure, and if this is the best way to go about it (instead of using something like Token Multisender).
Here is the function:
function sendMultiple(address[] memory _redemptions, uint[] memory _values) public returns (bool) {
    require(_redemptions.length == _values.length);

    uint256 senderBalance = balances[msg.sender];
    uint256 length = _redemptions.length;
    for (uint i = 0; i < length; i++) {
        uint value = _values[i];
        address recipient = _redemptions[i];

        require(senderBalance >= value);
        if (msg.sender != _redemptions[i]) {
            senderBalance -= value;
            balances[recipient] += value;
        }

        emit Transfer(msg.sender, recipient, value);
    }

    balances[msg.sender] = senderBalance;
    return true;
}

Thanks!


texts: How to extract the block sealer identity from the extraData hexbytes (which is renamed proofOfAuthorityData) in web3.py?

texts:
Question is in the tittle. I use a local network with PoA clique and middleware

 w3 = Web3(IPCProvider('~/mygethnode/geth.ipc'))
 w3.middleware_onion.inject(geth_poa_middleware, layer=0)

And then after a block is mined I obtain the field

block.proofOfAuthorityData.hex()

'0xd88301090b846765746888676f312e31332e38856c696e757800000000000000a341b5fea1e965d8319605ee083c12db3c28b9ed1d580d1f388494e21cabc71124fb8678b465168037c3c237dbebf774c58c01e3cf74c89534fd8e78eace0e0901'

Which, from my understanding of PoA, should contain the information regarding the sealer of that block.


texts:
So this works:

 pragma solidity ^0.4.11;

  contract test{
    event Print(string _name, uint _value);
    function test() payable{
        uint testval = 5;
        Print('val',(testval * 1000000000000000000));
        Print('val2',(5 ether));
    }
  }

And I get the same value for val1 and val2.  Is there anyway to do:

Print('val3',(testval ether);

I keep getting an error on the function and multiplying out my contract value by that amount is rather annoying


texts:
I was following Are there well-solved and simple storage patterns for Solidity? and ended up creating Mapped Structs with Delete-enabled Index to make sure that my array doesn't grow infinitely, when I just need only few indexes at any instant, but turns out the gas cost doubled after the implementation!

So now I have switched back to Simple List Using Array having index as the id of the element. I will be deleting (basically setting to 0) the array elements but won't be shifting elements.

In this case, is the gas cost going to be fix or is it linear with the size of the array. What if the array's size becomes more than 10K, 100K or more!


texts: How can the global registrar be called from a contract?

texts:
I want to call what i would do in geth with registrar.owner(namevar) from a solidity contract.

Is this possible - and how?


texts:
I was wondering about the immutabilty part of blockchain. I have written a good number of smart contracts but, recently I used delete and you can remove the data in the blockchain. Now, the data deleted will be there in some older blocks so is there way to get it?

I stumbled upon this question when I was searching for an answer.


texts: I'm trying to swap ETH to WETH tokens within contract, but cannot find any information how to do it. Can anybody help? Thanks!


texts: How to avoid/detect multiple internal transaction out-of-gas side effects?

texts:
Following an issue I opened in github, this bothers me. The operation described in the issue, which happened during following avsa's tutorial on creating a DAO, generated two internals transactions as evident here:

 Shortly, the internals transactions are:

Change the status of the requested operation in the DAO to "completed"
Actually perform the operation by sending a transaction to another contract

The first internal transaction completed successfully - that means updating the operation in the DAO to "completed" status. The second one fails, most likely because it went out of gas (multiple attempts produced the same results, while adding 100,000 gas made it work multiple times).

I think the implications of something like this happening in a real DAO are clear. I (mistakenly) assumed the if the second transaction ran out of gas, then the entire operation (including the first transaction) will revert.

As suggested by eth's comment, I will ask a specific question about this situation - how can I detect it inside the contract? Will changing the order of the operations help?


texts:
I am developing an app that is using the etherscan-api package.

I use it to get the contract ABI.

The problem is that I retrieve it via the API every time the function is called.

My question is: Can a Contracts ABI change at any point and can I just store the ABI json in a database field to reduce processing time?


texts: Does gas price increase under heavy load?

texts: Does Ethereum adjust and increase its gas price during times when there is high demand?


texts:
I have a Contract Template (Say contract ABC).  The constructor takes in 3 fields to initialize a contract.   I built in logic within the constructor to return a bool based on data checks.   The constructor should fail and not create a valid Contract if the data fields fails validation.  The return is a bool.

function ABC(bytes32 _field1, bytes32 _field2, bytes32 _field3) returns (bool isSuccess);

Now when I try to create a new contract (from another contract):  How do I check for the bool (Success).

I create an instance of the contract as:

ABC local = new ABC(_field1, _field2, _field3);

Is there a way to check if this was success - based on the bool return from the Constructor.

Alternative 1: I can do the data checks before I send the request to the Constructor.   I was trying to avoid rewriting the same code in multiple locations.

Alternative 2: I can initialize a field isValue within the constructor and check for it when validating an instance.

Any advise?  Thanks,


texts: Function burnfrom error: gas required exceeds allowance or always failing transaction

texts:
I have created a contract using Remix.

When I run the function burnFrom(), it shows:

gas required exceeds allowance or always failing transaction.

What am I doing wrong?

function burnFrom(address _from, uint256 _value) onlyOwner public returns
(bool success) {
    require(balanceOf[_from] >= _value);
    require(_value <= allowance[_from][msg.sender]);
    balanceOf[_from] -= _value;
    allowance[_from][msg.sender] -= _value;
    totalSupply -= _value;
    emit Burn(_from, _value);
    return true;
}


texts: Calling function of another contract in constructor not working anymore

texts:
I have a contract ElectionMaster that contains an array with all elections available in the network. When I create a new Election it calls a function addElection from ElectionMaster and registers itself. Everything used to work just fine in my private network, but suddenly it fails all the time. It still works in remix by using the JavaScriptVM but it fails when it tries the first interaction with ElectionMaster. Here are the simplified contracts (It successfully deploys ElectionMaster, but any attempt on Election fails at the second line in the constructor, when I check whether the user is an organiser or not, at STATIC CALL opcode). The weird part is that it used to work, but now it works only in JavaScriptVM. And of course that I checked the address of ElectionMaster and it is the correct one:

pragma solidity 0.5.4;
contract ElectionsMaster {

address private ownerMasterAddress = msg.sender;

address[] private elections;
bytes32[] private electionsNames;

mapping(address => uint8) private organizersMapping;

constructor() public {
    organizersMapping[msg.sender] = 1;
}

modifier isMasterAccount(address senderAddress) {
    require(senderAddress == ownerMasterAddress, "Master privileges required");
    _;
}

modifier isOrganizer(address senderAddress) {
    require(organizersMapping[senderAddress] != 0, "Organizer privilleges required");
    _;
}

function () external payable {
}

function changeOwnerMasterAccount(address newOwnerMasterAccount) public isMasterAccount(msg.sender) {
    organizersMapping[newOwnerMasterAccount] = 0;
    ownerMasterAddress = newOwnerMasterAccount;
    organizersMapping[newOwnerMasterAccount] = 1;
}

function addOrganizer(address newOrganizer) public isMasterAccount(msg.sender) {
    organizersMapping[newOrganizer] = 1;
}

function getBalance() public view isMasterAccount(msg.sender) returns(uint) {
    return address(this).balance;
}

function addElection(address electionAddress,
                    bytes32 electionName,
                    address organizerAddress) public isOrganizer(organizerAddress) {
    elections.push(electionAddress);
    electionsNames.push(electionName);
}

function getElectionAddresses() public view returns(address[] memory) {
    return elections;
}

function getElectionNames() public view returns(bytes32[] memory) {
    return electionsNames;
}

function canAddressDeployContract(address organizerAddress) public view returns(bool) {
    return (organizersMapping[organizerAddress] == 1);
}

}

and Election:

pragma solidity 0.5.4;

contract ElectionMaster {
function addElection(address electionAddress,
    bytes32 electionName,
    address organizerAddress) public {}

function canAddressDeployContract(address organizerAddress) public view returns(bool) {}
}

contract Election {

ElectionMaster private electionMaster;
mapping(address => uint8) private voters;
bytes32 private electionName;

constructor(address masterContractAddress, bytes32 nameOfElection) public {
    electionMaster = ElectionMaster(masterContractAddress);
    bool canDeploy = electionMaster.canAddressDeployContract(msg.sender);
    require(canDeploy == true, "Organizer permissions required to deploy a contract.");
    electionMaster.addElection(address(this), nameOfElection, msg.sender);

    electionName = nameOfElection;
}
}


texts:
I'm trying to understand ERC20 tokens. This page indicates that we can implement merged mining with the following code:

function giveBlockReward() {
    balanceOf[block.coinbase] += 1;
}

Newbie question: Someone will have to pay to call this function, right? Is there a way for the contract to call it automatically?

I've seen that the following code needs to be added to prevent abuses (source: Are mineable tokens possible?)

uint lastBlockRewarded;
function giveBlockReward() {
  if (lastBlockRewarded >= block.number)
    throw;
  lastBlockRewarded = block.number;
  balanceOf[block.coinbase] += 1;
}

If the function isn't called for a few blocks, then called for the last one, some blocks will be lost?

Thanks!


texts: parity CLI "bash: parity: command not found"

texts:
How do I run the parity CLI?  I installed it from here but running parity on the command line results in "bash: parity: command not found"

I'm trying to cancel pending transactions in parity during this crazy network congestion with the help of "parity --no-persistent-txqueue"

I installed via the wizard.  Not sure what location it installed to.  I also tried via brew based on their docs but brew can't seem to find parity.

Pako-2:~ pako$ brew install parity
Error: No available formula with the name "parity"
==> Searching for similarly named formulae...
Error: No similarly named formulae found.
==> Searching taps...
Error: No formulae found in taps.
==> You haven't updated Homebrew in a while.
A formula for parity might have been added recently.
Run `brew update` to get the latest Homebrew updates!
Pako-2:~ pako$ brew update
Already up-to-date.
Pako-2:~ pako$ brew install parity
Error: No available formula with the name "parity"
==> Searching for similarly named formulae...
Error: No similarly named formulae found.
==> Searching taps...
Error: No formulae found in taps.
==> You haven't updated Homebrew in a while.
A formula for parity might have been added recently.
Run `brew update` to get the latest Homebrew updates!
Pako-2:~ pako$ brew install parity --stable
Error: No available formula with the name "parity"
==> Searching for similarly named formulae...
Error: No similarly named formulae found.
==> Searching taps...
Error: No formulae found in taps.
==> You haven't updated Homebrew in a while.
A formula for parity might have been added recently.
Run `brew update` to get the latest Homebrew updates!
Pako-2:~ pako$


texts: I am using Ubuntu 20.04 for creating a private ethereum blockchain using geth. I am required to load the "Simple.abi" script present inside home/contract. But when I give the file-path in the loadScript it returns undefined even though my path is correct with respect to the home. Can anyone tell me their quick thoughts about what the issue is??


texts:
I have a ERC 20 token platform the token: BTZ
botztoken
and what I am wanting to do is figure out what I can do with
the tokens as utility tokens to accomplish teams mission which is:
to help veterans and seniors in times of needs. Am putting a community of people together that we want them to share the tokens and earn them by giving and sharing.


texts: Parity default "token deployment" Dapp issue

texts:
I'm using Parity 1.4.6 testnet on OSX.
When I'm trying to test default token deployment Dapp,

transaction sending responds with "Transaction cost exceeds current gas limit. Limit: 5183626, got:60000000. Try decreasing supplied gas."

Why is token deployment so expensive? Is it possible to avoid such error for this Dapp?


texts: Dynamic & static arrays - data structures

texts:
I am programming a card game for fun to learn solidity. I have noticed that there seems to be a lack of data structures to use apart from dynamic/static arrays & mappings.

For example I have

struct Character {
    bool engaged;
    string name;
    string charType;
    uint dna;
    uint weaponCounter;
    uint armourCounter;
    uint battleCounter;
    uint16 level;
    CharacterStatistics charStats;
    mapping (uint => WeaponStats) weapons;
    mapping (uint => ArmourStats) armour;
    mapping (uint => BattleStatistics) battleStats;
}
/// @notice An array(vector) of Characters.
Character[] public characters;

/// @notice Dictionaries that get the owners total characters & get a character owner from the characters id.
mapping (uint => address) public characterToOwner;
mapping (address => uint) public ownerCharacterCount;

I can build a data structure that is essentially a vector of characters and some mappings.

But what would be required to introduce a binary tree in solidity, or any other type of tree structure?


texts: Can Solidity function modifiers access function arguments?

texts:
I would like to have a modifier that looks like this:

modifier restrictTargetType(uint contractType) {
    if (contractTypes[target] != contractType) { throw; }
    _
}

Where target is an address passed as a function argument. Simply naming the function argument target isn't sufficient, and gives me an Error: Undeclared identifier.


texts:
I'm listening to events of my deployed contract. Whenever a transaction gets completed and event is fired receiving the response causes following error:

  Uncaught Error: Returned values aren't valid, did it run Out of Gas?
      at ABICoder.push../node_modules/web3-eth-abi/src/index.js.ABICoder.decodeParameters
  (index.js:227)
      at ABICoder.push../node_modules/web3-eth-abi/src/index.js.ABICoder.decodeLog
  (index.js:277)

Web3 version: 1.0.0-beta36

Metamask version: 4.16.0

How do I fix it?


texts: I have a Nvidia Geforce GT 650T version 369.09 with 4Go memory, i want to try mining ethereum using a Cuda based miner, i've read that geth and eth didn't support cuda so is there any fork or another miner to use it? Thank you


texts: Where is the private key for a contract stored?

texts: This is a question that I am asked often by developers who assume that a contract has a private key of its own to sign any transactions that it makes.


texts: Why does etherscan show such unusual results for the creation of this specific contract?

texts:
Normally, when I browse for the address of a specific contract and then click the contract-creation transaction label, I get:

To: [Contract 0x... Created]

For example, consider the BNB contract at 0xb8c77482e45f1f44de1745f52c74426c631bdd52.

When you open this link, you'll see on the More Info pane:

ContractCreator: 0x00c5e04176d95a... at txn 0x436fc7d21ed4a0a...

When you then click the address next to the txn label, you'll see:

To: [Contract 0xb8c77482e45f1f44de1745f52c74426c631bdd52 Created] (Binance Token)

However, when I do this on 0x607108c46bce4cf6f86698e9b46e3270a734fefe, I get:

To: Contract 0x584b3fb1267bf10b85434ccbbe95c2fe677e33eb

To be honest, it truly bothers me when I use etherscan's API in an automation script of mine, with the purpose of finding the creation block numbers of various contracts:

const request = require("request");

const ADDR = process.argv[2];
const KEY  = process.argv[3];
const URL  = "http://api.etherscan.io/api?module=account&action=txlist";

request(URL + "&address=" + ADDR + "&apikey=" + KEY, function(error, response, body) {
    const parsed = body ? JSON.parse(body) : {};
    if (parsed.result && parsed.result.length > 0) {
        if (parsed.result[0].to == "") {
            console.log(parsed.result[0].blockNumber);
        }
        else {
            console.log("error");
        }
    }
    else {
        console.log("error");
    }
});

Normally, on a contract-creation transaction, the value of body.result[0].to is "".

However, in this unique case, it is not.

Any idea why?

I am guessing that maybe this contract was created by another contract (via new) and not by an externally-owned account (in other words, that it was created "on-chain" instead of "off-chain").

But it still doesn't make sense to me that the to address is known upon contract-creation (I mean, of course it can be computed from the hash of the concatenation of the deployer's address and the deployer's nonce, but that would work whether the contract was created "on-chain" or "off-chain").

So what exactly was special about the creation of this specific contract, which makes etherscan return different results?

Thank you!


texts: Miner incentives in a permission blockchain with a digitally native asset on Ethereum?

texts:
Would be very grateful if someone could give me their opinion and ideas on whether this is possible, and if so, how this might be done:

If one were to build a permission blockchain on Ethereum with it's own native coin, how could consensus be reached? And more importantly, how could miner incentives work in such a system? Miners could be internal or external to the system, but I wouldn't want the miners to interact with the utility token (unless internal to the system), albeit whether external or interna,they would receive the gas token as transactions fee fees from the blockchain users.

Tricky question... would appreciate your thoughts.


texts: how to set gas limit & fix UNPREDICTABLE_GAS_LIMIT error

texts:
The function below works fine until the point where await thePool.exchange(fromCoin, amountToSell, toCoin); is called - I get:
error: UNPREDICTABLE_GAS_LIMIT,
reason: 'cannot estimate gas; transaction may fail or may require manual gas limit',
I want to set the gas limit, but don't know how to. I've looked on the ethers docs and found that
transactionRequest.gasLimit ⇒ BigNumber | Promise< BigNumber >

The maximum amount of gas this transaction is permitted to use.`

No idea how to implement it though. I've tried await thePool.exchange(fromCoin, amountToSell, toCoin, {gasLimit: 2000000}); but still the same result
// Executes the trade
async function executeTrade(fromCoin, toCoin, amountOfFromCoin) {
  // Loads the pool address we're using
  const thePool = await factory.loadPool(globalPoolAddress);

  // Sets amount to sell & converts to string
  const amountToSell = amountOfFromCoin.toString();
  try {
    console.log("Commencing pool.exchange with $"+(amountToSell/(10 ** 18))+" of "+fromCoin+" pool to " +toCoin);
    await thePool.exchange(fromCoin, amountToSell, toCoin);

    return {
      "status": "success",
      "data": "Exchanged $"+(amountToSell/(10 ** 18))+" of "+fromCoin+" pool to "+toCoin,
    };
  } catch (err) {
    console.log(err);
    return {
      "status": "fail",
      "msg": err,
    };
  }
}

  [1]: https://i.stack.imgur.com/7W5a9.png


texts: What are the odds of getting same address or private-key or 12/24 set of mnemonic to 2 different people

texts:
Questions!!

What are the chances that 2 people get the same set of those 12 or 24-word mnemonic??

In web3.js, there is a function ' web3.eth.accounts.wallet '... It spits out a set of accounts and private keys...
What are the odds of getting the wallet or address ?? (I think its related to the question above)

(Noobie question) Let's say I generated a wallet. now,

is it possible to create 12/24 mnemonic from that wallet (mostly no but still I need your point of view)
If I want to create my own wallet using javascript, how can I get that functionality to generate that set of mnemonic (a feature used by Metamask)


texts:
I am on GETH, 1.9.23 and I have had a smart contract running for more than 3 months now.
Suddenly, all transaction failed with "exceeds block gas limit".
I checked the Ropsten Testnet and there is no maintenance going on.
May I know what else do I need to check? I am a bit lost.


texts: Weighted Random Number Array generation in solidity

texts:
I have an array like this in the array,

uint256[] public numberArr= [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

Each number in an array have their own weight,

uint256[] public weightNumberArr = [1, 3, 9, 7, 15, 18, 36, 22, 12, 6];

Here you can say that the weight of number 0 is 1 and for number 2 it is 3 like that. So here Chance of arriving number 6 is more than a chance of arriving number 0.

How can I generate a random number array of 0 to 9 by using weighted probability in solidity?

Any help will be highly appreciated!


texts:
I have a question for you guys. I have 2 contracts:

contract House {
  uint public idHouse;
  ...
}

contract ArrayHouse {
  House[] public arrayHouse;

  function getHouse(uint n) returns(House){
    if (n >= arrayHouse.length)
      throw;
    return arrayHouse[n];
  }
}

I compiled and migrated the contract ArrayHouse to the testrpc reseau. Then, I went to truffle console and tried the following javascript:

arrayHouse=ArrayHouse.new(...);
arrayHouse.then(function(inst1){meta=inst1;return meta.getHouse(0)}).then(function(inst2){return inst2.idHouse.call();})

I got the following error:

TypeError: Cannot read property 'call' of undefined
    at evalmachine.<anonymous>:1:84
    at process._tickDomainCallback (internal/process/next_tick.js:129:7)

I wonder why I cannot access to the an attribute(public idHouse) of an element(House) of my array(arrayHouse). Anyone has an idea?


texts: How to set the nonce in offline transaction?

texts:
Let's suppose, I already executed 48 Tx onchain and I signed an offchain Tx with nonce 49.

Now, If:

I don't sign the offchain Tx with nonce, the transaction will be
invalid because every Tx must have nonce to protect against replay
attach.
I make an onchain Tx with 49 nonce, the offchain signed Tx
will automatically get void as network will not accept
another Tx with similar nonce.
I make an onchain Tx with nonce 50
(instead of 49 as stated above), my tx will stay in pending state
until and unless a Tx with 49 nonce is not executed.

There are so many problems in Offchain signing of Tx. How to overcome these problems?


texts: What is the purpose of the variable "maxlength" in this function?

texts:
I am trying to understand the function "appendUintToString" from Solidity concatenate uint into a string?  The function is recreated below.  For now, I am trying to understand what the integer "maxlength" does.

 function appendUintToString(string inStr, uint v) constant returns (string str) {

    uint maxlength = 100;

    bytes memory reversed = new bytes(maxlength);
    uint i = 0;
    while (v != 0) {
        uint remainder = v % 10;
        v = v / 10;
        reversed[i++] = byte(48 + remainder);
    }
    bytes memory inStrb = bytes(inStr);
    bytes memory s = new bytes(inStrb.length + i);
    uint j;
    for (j = 0; j < inStrb.length; j++) {
        s[j] = inStrb[j];
    }
    for (j = 0; j < i; j++) {
        s[j + inStrb.length] = reversed[i - 1 - j];
    }
    str = string(s);
}

When I isolate it in Remix with the following code, the getter for "reversed" returns an empty 0 slot, but the numbers in the slot match the maxlength integer.  So, when maxlength = 20, returnBytes returns 0x0000000000000000000000000000000000000000, and if maxlength = 2, it returns 0x0000, and so on.

This suggests that the maxlength integer provides a limit for how many bytes can be represented with "reversed".  Yet, when I set "reversed" with the changeBytes function, there seems to be no limit.  If maxlength = 2, for example, it will allow me to input three or more in this function and the getter function will then return three or more (it doesn't cut off the extra).  So then what is the point of maxvalue?

uint public maxlength = 20;
bytes reversed = new bytes(maxlength);

function changeBytes(bytes _bytes) public {
reversed = _bytes;
}

function returnBytes() public view returns(bytes) {
return reversed;

}


texts: How to get private through UTC files in keystore

texts:
I create accounts by geth account new with a password, then I get a UTC file which is a json file saved in folder keystore under data directory. Now I am attempt to get private key from this json file.

The reason I want to do this is because I am using metamask un ubuntu and there is an issue that does not allow me to import json file directly into  metamask under ubuntu.

Anyone knows how to get private key through UTC json file with password?

Thank you


texts: Does it align to the base concept of blockchain, if one stores the hash value generated from IPFS network in a database?

texts: A friend of mine utilized IPFS to store data files regarding some user info.But for an android application of the same, he retrieved all hash values(same user but different files) and stored it in a database.I claimed that the base concept of decentralization wasn't achieved by it but he said that it's not the case. Could anyone comment on this?


texts: Send Data into BlockChain Network using w3?

texts:
HI I want to store my bank information on ethereum network using w3.
can anyone help me to send my data

//Bank.sol

pragma solidity >=0.4.21 <0.6.0;
contract Bank
{
    struct User
    {uint userId;
     string email;
     string name;
    }

    mapping(uint => User) public users;
    mapping(uint => string) public userRequestStatus;
    mapping(uint => uint256) public balance;

    function createUserRequest(uint userId_, string memory email_, string memory name_, uint256 amount_ ) public
    {
        require(users[userId_].userId != userId_,"User Already Exist.");
        User memory user = User( {userId: userId_ , email: email_, name: name_});
        users[userId_]= user;
        balance[userId_] = amount_;
        userRequestStatus[userId_] = "Request send to bank";

    }

    function UpdateAmountRequest(uint userId_, uint256 amount_ ) public
    {
        require(balance[userId_]== 0,"no data available");
        balance[userId_] = amount_;
        userRequestStatus[userId_] = "after updating balance request in bank";

    }

    function getUserInfo(uint userId_ ) public  view returns(uint userId, string memory email,string memory name)
    {
        User memory user = users[userId_];
        return (user.userId, user.email, user.name);

    }
    function getUserAmount(uint userId_ ) public  view returns(uint256)
    {
        return balance[userId_];

    }

}

//index.js

var web3 = new Web3(new Web3.providers.HttpProvider("https://rinkeby.infura.io/myAPI"))

var contractInstance = new web3.eth.Contract(contract.abi, "my Address")
contractInstance.createUserRequest.call(1,"laxman@gamil.com", "laxman", 1000).call((err, result) => {
    console.log("result", result) ;
    console.log("reerrsult", err) ;
})


texts: Accessing the Ethereum State Variables using web3js (Java Script)

texts:
I'm trying to run the below code to get the state variables using the getIdBytes method of the Smart Contract, and assign it to a java script array variable, but it doesn't seem to work.

All I can do is print the returned values using console.log(return).

Can someone point me in the right direction please?

var coreValues = ['Apple', 'Banana'];
console.log("Before call :"  + coreValues[1]);

if (get_flag)
{
contract3.methods.getIdBytes(index1, abstract_contract_address).call().then(function(result){
   for (var i = 0; i < 5; i++) {
  coreValues[i] =  result[i];
  console.log("Inside Function Call" + coreValues[i]);
  }
});

console.log("After Call :" + coreValues[0]);

Here's what the output looks like.

Before call :Banana
After Call :Apple
Inside Function call : Steve
Inside Function call : Rogers
Inside Function call : Male
Inside Function call : 0987654
Inside Function call : 12/05/1980

Should I be using events?


texts:
I am trying to determine the behavior of call when executed from a constant function.

Of course, the compiler issues a warning on that:

  Warning: Function declared as view, but this expression (potentially) modifies the state and thus requires non-payable (the default) or payable

But since this is not an error, I can move forward and see what happens.

Please note that I'm on Solc 0.4.25; I'm pretty sure that things have changed on Solc v0.5.x.

Anyway, I went ahead and implemented a pair of small contracts in order to test this:

pragma solidity 0.4.25;

contract Callee {
    uint256 public xxxx;

    function func() external returns (uint256) {
        xxxx = 123;
        return 456;
    }
}

contract Caller {
    Callee private callee = new Callee();
    uint256 public yyyy;

    function callFromConstantFunc() external view returns (uint256) {
        uint256[1] memory retv;
        address dest = address(callee);
        bytes memory selector = abi.encodeWithSelector(callee.func.selector);
        assembly {
            let status := call(gas, dest, 0, add(selector, 32), mload(selector), retv, 32)
            if iszero(status) {
                revert(0, 0)
            }
        }
        return retv[0];
    }

    function callFromNonConstantFunc() external returns (uint256) {
        uint256[1] memory retv;
        address dest = address(callee);
        bytes memory selector = abi.encodeWithSelector(callee.func.selector);
        assembly {
            let status := call(gas, dest, 0, add(selector, 32), mload(selector), retv, 32)
            if iszero(status) {
                revert(0, 0)
            }
        }
        yyyy = retv[0];
    }

    function xxxx() external view returns (uint256) {
        return callee.xxxx();
    }
}

Then I tested both methods via Truffle:

contract("Test", function(accounts) {
    it("callFromConstantFunc", async function() {
        const caller = await artifacts.require("Caller").new();
        const retv = await caller.callFromConstantFunc();
        const xxxx = await caller.xxxx();
        console.log(`retv = ${retv}, xxxx = ${xxxx}`);
    });
    it("callFromNonConstantFunc", async function() {
        const caller = await artifacts.require("Caller").new();
        await caller.callFromNonConstantFunc();
        const retv = await caller.yyyy();
        const xxxx = await caller.xxxx();
        console.log(`retv = ${retv}, xxxx = ${xxxx}`);
    });
});

The results are rather staggering IMO:

callFromConstantFunc: retv = 456, xxxx = 0
callFromNonConstantFunc: retv = 456, xxxx = 123

As you can see, when I invoked Callee.func from Caller.callFromConstantFunc, the transaction has completed without reverting, but the value of Callee.xxxx has remained unchanged.

For the record, I have also invoked Callee.func from Caller.callFromNonConstantFunc, where the value of Callee.xxxx has changed as expected.

Of course, changing call to staticcall would cause both Caller functions to revert, because the Callee function itself is not constant.

However, my question focuses on the behavior of call, and I'm trying to figure out how it is possible for a transaction to complete successfully and yet - without "doing the job".

Some clarification on the parameters that I pass to call:

gas - the remaining amount of gas for the transaction
dest - the address of the Callee instance
0 - the amount of wei passed to the function
add(selector, 32) - the start address of the input (see explanation below)
mload(selector) - the length of the input (see explanation below)
retv - the start address of the output
32 - the length of the output

Because selector is a bytes array, the first 32 bytes contain the length of this array, and the actual data starts immediately after.

I have executed the test via Ganache.

Can someone please confirm that this is the expected behavior if I deploy such contract to a "real" network? Also, how is it even possible for this kind of behavior to be "allowed" on Ethereum?

Thank you.


texts: How to send context from DrizzleContext.Provider to a Class Component / Class Container

texts:
I'm using the new Context API supported 'drizzle-react' library in my dapp. Can anyone please clarify how to receive the context sent from DrizzleContext.Provider into a "class" component? Check out the example index.js file below. Imagine the < App /> component is a "class" component and not a "function component". For a "function" component, i guess it is pretty straightforward - use < DrizzleContext.Consumer >. But how to get the context (drizzle = {drizzle}) inside the class component ? I tried giving a constructor with context prop like this:

constructor(props,context) {...}

but this doesnt work. Any ideas ?

my index.js looks like this:

<!-- language: lang-jsx -->
    import React from 'react';
    import ReactDOM from 'react-dom';
    import { Drizzle, generateStore } from "drizzle";
    import { DrizzleContext } from "drizzle-react";
    import { LoadingContainer } from 'drizzle-react-components'
    import './index.css';
    import App from './App';
    //import * as serviceWorker from './serviceWorker';
    import drizzleOptions from './drizzleOptions';

    const drizzleStore = generateStore(drizzleOptions);
    const drizzle = new Drizzle(drizzleOptions, drizzleStore);

        ReactDOM.render(
            (<DrizzleContext.Provider drizzle={drizzle} >
                    <App />
            </DrizzleContext.Provider>),
            document.getElementById('root')
        );


texts: How to edit a contract that has already been deployed?

texts:
I have been writing my first few contracts. So, as I understand it, once you write, compile, and deploy your contract, the only way to then interact with that contract is via something like web3.js and the ABI Definitions within the contract itself.

My question is: How does one update the contract itself after it has been deployed? What if something went wrong, or you want to make improvements within the contract code itself?

Is this possible, or something you need to setup via the ABI definitions in the first place. Just seems hard that I would know what to expect in the future, but then again maybe I am thinking of this completely wrong. Any help would be greatly appreciated.


texts: Why my geth fast node suddenly stopped running?

texts:
Fatal: Error starting protocol stack: gap (#3) in the chain between ancients and leveldb

when I run geth node for ropsten by :

geth --testnet --syncmode "fast" --cache=512 --rpc --ws --shh console

It throws Error:

INFO [09-11|21:33:55.437] Maximum peer count                       ETH=50 LES=0 total=50
INFO [09-11|21:33:55.437] Smartcard socket not found, disabling    err="stat /run/pcscd/pcscd.comm: no such file or directory"
ERROR[09-11|21:33:55.438] Failed to enumerate USB devices          hub=ledger vendor=11415 failcount=1 err="failed to initialize libusb: libusb: unknown error [code -99]"
ERROR[09-11|21:33:55.438] Failed to enumerate USB devices          hub=trezor vendor=21324 failcount=1 err="failed to initialize libusb: libusb: unknown error [code -99]"
ERROR[09-11|21:33:55.438] Failed to enumerate USB devices          hub=trezor vendor=4617  failcount=1 err="failed to initialize libusb: libusb: unknown error [code -99]"
ERROR[09-11|21:33:55.438] Failed to enumerate USB devices          hub=ledger vendor=11415 failcount=2 err="failed to initialize libusb: libusb: unknown error [code -99]"
ERROR[09-11|21:33:55.438] Failed to enumerate USB devices          hub=trezor vendor=21324 failcount=2 err="failed to initialize libusb: libusb: unknown error [code -99]"
ERROR[09-11|21:33:55.438] Failed to enumerate USB devices          hub=trezor vendor=4617  failcount=2 err="failed to initialize libusb: libusb: unknown error [code -99]"
INFO [09-11|21:33:55.440] Starting peer-to-peer node               instance=Geth/v1.9.3-stable-cfbb969d/linux-amd64/go1.11.5
INFO [09-11|21:33:55.440] Allocated trie memory caches             clean=128.00MiB dirty=128.00MiB
INFO [09-11|21:33:55.440] Allocated cache and file handles         database=/root/.ethereum/testnet/geth/chaindata cache=256.00MiB handles=524288
INFO [09-11|21:33:55.641] Opened ancient database                  database=/root/.ethereum/testnet/geth/chaindata/ancient
Fatal: Error starting protocol stack: gap (#3) in the chain between ancients and leveldb

I tried to delete ancient directory from chaindata but got this:

 Error starting protocol stack: ancient chain segments already extracted, please set --datadir.ancient to the correct path


texts: Ethereum transaction fails in simultaneous calls

texts:
I am making two calls simultaneous call with a single wallet. First I am making a contract call then I am making a ether transaction call. The first call succeeds, but the next call fails. I got this below error

Error: replacement fee too low

Is there any way I can succeed both call?

Also how to manage transactions if more than 10 users make simultaneous transactions on a single wallet?

Thanks


texts: Mac OSX: I have created a launchagent plist for Geth so it runs in the background on startup. Can I reattach it to terminal?

texts:
I wanted to be able to run Geth in the background without having to think about it in order to assist the network. So I created a .plist and added it to /library/launchagents. Now when I start my computer, Geth starts up and runs in the background.

However there are times that I want to be able to interact with Geth and view the running script in Terminal. Is it possible to reattach Geth to Terminal?

If not, can anyone recommend a better way that I can run Geth in the background?

Thanks


texts:
I am using balancer.exchange to swap Dai for xHDX.
It says the swap was successful but did not swap. I still have my Dai and did not get the xHDX.
https://etherscan.io/tx/0x07a43b7fca5eec146566dfc7f3a983bb6ccbc28925c2098837915d4aaf4b0fe8
Not sure what to do to fix this? Or did I just loose the ETH Gas fee and the swap messed up?
Thank you.


texts:
I'm trying to understand some basis of Solidity,
I get how to get multiple values from one query, but don't really understand how to store them, could anyone explain me how to do it?

pragma solidity ^0.4.22;
import "github.com/provable-things/ethereum-api/provableAPI_0.4.25.sol";

contract ExampleContract is usingProvable {

   string public ethprice;
   string public ethvolume;
   event LogConstructorInitiated(string nextStep);
   event LogPriceUpdated(string price);
   event LogNewProvableQuery(string description);

   function ExampleContract() payable {
       LogConstructorInitiated("Constructor was initiated. Call 'updatePrice()' to send the Provable Query.");
   }

   function __callback(bytes32 myid, string memory[] result) {
       if (msg.sender != provable_cbAddress()) revert();
       ethprice = result[0];
       ethvolume = result[1];
       LogPriceUpdated(result);
   }

   function updatePrice() payable {
       if (provable_getPrice("URL") > this.balance) {
           LogNewProvableQuery("Provable query was NOT sent, please add some ETH to cover for the query fee");
       } else {
           LogNewProvableQuery("Provable query was sent, standing by for the answer..");
           provable_query("URL", "json(https://api.pro.coinbase.com/products/ETH-USD/ticker).[price,volume]");
       }
   }
}


texts: couldnt understand implementaion of UpgradeabilityProxyFactory

texts:
I want to use UpgradeabilityProxy provided by zeppelin, they have one method createProxyAndCall which they say initialize the new implementation with data parameter we provided which looks like:

   * @dev Creates an upgradeability proxy with initial implementation and calls it.
   * This is useful to initialize the proxied contract.
   * @param implementation Address of the initial implementation.
   * @param serviceRegistry service registry
   * @param data Data to send as msg.data in the low level call.
   * It should include the signature and the parameters of the function to be
   * called, as described in
   * https://solidity.readthedocs.io/en/develop/abi-spec.html#function-selector-and-argument-encoding.
   * @return Address of the new proxy.
   */

  function createProxyAndCall(
    address implementation,
    address serviceRegistry,
    bytes data
  ) public payable returns (MaintainableUpgradeabilityProxy) {
    MaintainableUpgradeabilityProxy proxy = _createProxy(implementation, serviceRegistry);
    // proxy.changeAdmin(owner);
    /* solium-disable-next-line */
    require(address(proxy).call.value(msg.value)(data), "failed to call proxy with data");

    if (autoActivate) {
      Activatable(address(proxy)).activate();
    }

    return proxy;
  }

1) I am confused with how it is initializing the data, can someone please help me understand what this line is doing?

require(address(proxy).call.value(msg.value)(data), "failed to call proxy with data");

reference link: openzep

2) Also can you please tell me how to pass data to the given function, if my logic contract needs 3 parameters of String, uint and address type how shall I pass that in function createProxyAndCall()?


texts: Unable to unlock account with Parity and Web3 on the testnet

texts:
I'm running a local Parity node for the testnet (Ropsten) on Debian (Jessie). I'm using web3.py to connect to this node and create transactions.

I've created a new account:

parity account new --chain ropsten

I'm running my parity node with the following options

/usr/bin/parity --chain ropsten --no-ui --rpcapi 'eth,web3,personal' --jsonrpc-interface 127.0.0.1 --bootnodes 'enode://20c9ad97c081d63397d7b685a412227a40e23c8bdc6688c6f37e97cfbc22d2b4d1db1510d8f61e6a8866ad7f0e17c02b14182d37ea7c3c8b9c2683aeb6b733a1@52.169.14.227:30303,enode://6ce05930c72abc632c58e2e4324f7c7ea478cec0ed4fa2528982cf34483094e9cbc9216e7aa349691242576d552a2a56aaeae426c5303ded677ce455ba1acd9d@13.84.180.240:30303'

When I test this node, it's running fine, see the following python shell:

Python 3.4.2 (default, Oct  8 2014, 10:45:20)
[GCC 4.9.1] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from web3 import Web3, KeepAliveRPCProvider, IPCProvider
>>> web3 = Web3(KeepAliveRPCProvider(host='localhost', port='8545'))
>>> web3.eth.blockNumber
1012932

However, when I try to unlock my account it returns False (with a proper account hash and password ofcourse)

>>> web3.personal.unlockAccount('my-account-hash', 'some-password')
False

When I check if it's actually in my list of accounts, I get the following:

>>> web3.personal.listAccounts
[]

Any ideas would be kindly appreciated.


texts: Sending Ether from an account in Node1 to another an account in Node2, both nodes are running in Same network

texts: [RESOLVED]I am trying to send ether from Account1 in Node1 to Account1 in Node2, both Node1 and Node2 are running under same network ID. I am able to send ether between accounts in same node but not between different accounts in different nodes. Error is "No key for given address or file".


texts:
I have a design where contract A is calling contract B, which then calls Oraclize a few times, and then sends the results back to contract A. The Oraclize calls could end up taking upwards of 30 minutes in certain cases.

Can I have contract B send the result back to contract A via a return value to the initial function call, even if it takes 30+ minutes to evaluate? Or do I have to use a callback function?

In other words, do Solidity functions time out?