texts: How to change the name from Ethereum on a private blockchain

texts:
So i followed some tutorials to make my own private version of ethereum, thats all good and working fine, but how can I change the name "Ethereum" "ETH" "ether" to basically have the name of my coin? what parts need changing?

A search and replace was not a good result :)


texts: What will a block look like post Casper?

texts:
Currently I think blocks look like [previous block hash + transactions + nonce], such that the hash of all that is less than the difficulty. After Casper what will it look like? I guess there is no point in the nonce and the hash of the block will be irrelevant.

After the switch to Casper is there anything stopping Ethereum being cloned and someone simulating it themselves and creating lots of valid blocks at no effort? With proof of work that couldn't have happened as they'd still have to mine to find the correct nonces.


texts: Using Truffle, Metamask and Ropsten to simulate two users

texts:
I'm trying to create an environment where I can test that access to a contract is restricted to a given wallet address, so I'm trying to simulate two users...

1) I'm running geth pointing to Ropsten test network, and have deployed a simple contract with Truffle, which I'm accessing locally via "truffle serve" at http://localhost:8080

2) I have two Chrome instances, "Person 1" and "Person 2" with Metamask wallets set to a separate account in each, both accounts are Ropsten accounts, created in my geth console.

3) When I point the Metamask wallets to the Ropsten network, I can successfully send transactions from each account to my contract and see the values in Ropsten via the etherscan browser, but - I can't successfully make any calls to "constant" functions, everything just returns a zero or a null (ie. in code below I can set the string, but not read it).

I think I'm on the right lines, but don't understand why my calls are not returning any data - anyone encountered similar, or have a good alternative solution to simulate two users?

[UPDATE: My scenario works if I use testrpc instead of Ropsten, so question remains - why can't I make a call to a constant function on Ropsten? ]

Thanks,
Iain

contract Message {

    address public owner = msg.sender;
    string public message = "Initial Message";

    function Message() public {
      message = "No message set - by constructor";
      owner = msg.sender;
    }

    function retrieveMessage() constant
       returns (string _messageString)
    {
      _messageString = message;
    }

    function setMessage(string messageString) {
      message = messageString;
    }

}

Javascript running via http://localhost:8080 served by Truffle...

 import message_artifacts from '../../build/contracts/Message.json'

 // Messages is our usable abstraction, which we'll use through the code below.
 var Messages = contract(message_artifacts);

 refreshMessage: function() {
     var self = this;

     var meta;
     Messages.deployed().then(function(instance) {
        var result = instance.retrieveMessage.call();
        return result;
     }).then(function(value) {
        var message_element = document.getElementById("secretMessage");
        message_element.innerHTML = value + ".";
     }).catch(function(e) {
        self.setStatus("Error getting message; see log.");
     });
}


texts: Guidelines for designing contracts to handle bugfixes?

texts:
Most introductory guides for contract design talk about creating "mortal" contracts (contracts that include some function that triggers a suicide() call), but what about if that contract was for some sort of sub-currency (Fungible Token/FT)? Is it possible to see the state of a contract as it existed immediately before suicide? So in theory someone could create a new contract that has its initial state mirroring what the old contract had?

I'm envisioning a situation where a contract/currency has been in circulation for a while and then an edge-case bug is discovered in the contract code. How to fix/correct it? It seems there needs to be at least some basic hooks programmed into the contract from the get-go to recover from a situation like that, but what are they?

The "creating a crypto-currency" guide talks about adding a freezeAssets call, which seems a good start; if need-be, the maintainer could freeze everyone's assets, which would keep the contract alive, and able to return queries about account's values. Then a new currency could be spun up that users could call some sort of transfer function to replicate assets in the new coin.

Since the address a contract gets created at is deterministic, would it be possible for a contract owner to suicide the old contract, and then deploy a new contract to the same address (which would mean re-use the nonce used when creating it in the first place)? Would a new contract at the same location have access to the same State as the previous contract (meaning everyone's alt-coins would be restored to the same state)?


texts:
Is there any built-in way of catching throw clauses?

For example, if I'm building a voting application where people must be given permission by the chairperson before voting, otherwise the contract throws.

Would it be possible to catch this throw in order to give the user a feedback of what happened without having to manually trigger an event?


texts:
I am researching about Factory contract to clone existing contracts, First is the implementation present at https://github.com/optionality/clone-factory/blob/master/contracts/CloneFactory.sol. I don't know what these 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000 and
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000 meant to do.

The other implementations just use the new keyword to make an instance of deployed smart contracts.
What's the difference between the two approaches?
How the code from optionality actually works? Is this implementation also works in new solidity versions ^0.6.0.

function createClone(address target) internal returns (address result) {
    bytes20 targetBytes = bytes20(target);
    assembly {
      let clone := mload(0x40)
      mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
      mstore(add(clone, 0x14), targetBytes)
      mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
      result := create(0, clone, 0x37)
    }


texts: I created mapping address-> uint and i need to make whole mapping -> uints values set to 0  is it possible?


texts: visual studio solidity extension for solidity >0.4

texts: I would like to know if the visual studio extension for solidity supports the release after 0.4, I think this extension is only for previous releases <= 0.3.5 while it was updated for the last time at 6/19/2016, is there any new update.


texts: How to solve eth_getFilterChanges looping when deploying with truffle (parity)?

texts:
I am using truffle migrate and I get some kind of loop which just endlessly prints out eth_getFilterChanges. How can this be solved?

I have used this truffle.js

module.exports = {
  networks: {
    development: {
      host: "127.0.0.1",
      port: 8540,
      network_id: "*", // Match any network id
      gas: 4699999,
      from: "0x004ec07d2329997267ec62b4166639513386f32e"
    }
  }
};

I used the DemoPoA setup at parity. I did a geth attach and it seems coinbase has a balance of zero.

   > ]
 <   [
 <     {
 <       "jsonrpc": "2.0",
 <       "result": [],
 <       "id": 23
 <     }
 <   ]
   > [
   >   {
   >     "jsonrpc": "2.0",
   >     "id": 24,
   >     "method": "eth_getFilterChanges",
   >     "params": [
   >       "0x7"
   >     ]
   >   }
   > ]
 <   [
 <     {
 <       "jsonrpc": "2.0",
 <       "result": [],
 <       "id": 24
 <     }
 <   ]


texts: Can I store data like an excel file on the Ethereum?

texts:
I am a university student studying Ethereum in South Korea. It is not a regular course but a personal study due to interest!

I would like to make a conceptual diagram of 'Smart Factory' using private ethereum blockchain.

Smart Factory uses several sensors: thermometer, hygrometer, accelerometer and so on.

I am currently curious about three things.

Numerous values measured by a sensor, for example an accelerometer measure 100 data per second for 10 minutes.

It is 60,000 data, and the data volume will be about 20mb (assumption).

Is it possible to store all of this data on all nodes of the ethereum blockchain at this time? Or can I just read the sensor value and do a simple command (raise the temperature in indoor, stop the machine and so on)? This is because the data is stored like an excel file, not as simple as the transaction data.

More simply, is it possible to store 'file data' in a block such as an excel file in an ethereum blockchain?

There is no need for 'ether trading' in the private ethereum blockchain that I envision. 'gas' prevents malicious users from falling into an infinite loop, but what does 'Ether' do in the case of me?

I am a complete starter. Ultimately, I'd like to implement a smart factory using few sensors(it's for PPT presentations, not for real), but knowledge has too many limitations.

Thank you so much for your answer to my question.

(I use this site for the first time. I posted the same question on stackoverflow. Is this wrong?)


texts: Solidity: Call an unimplemented function?

texts:
I am trying to understand some solidity code, and I see what appears to be the calling of an unimplemented function.
There is an interface defined as:
interface IOneInchCaller is ISafeERC20Extension, IGasDiscountExtension {
    struct CallDescription {
        uint256 targetWithMandatory;
        uint256 gasLimit;
        uint256 value;
        bytes data;
    }

    function makeCall(CallDescription memory desc) external;
    function makeCalls(CallDescription[] memory desc) external payable;
}

And then elsewhere in the codebase I see a call to this function:
function swap(
        IOneInchCaller caller,
        SwapDescription calldata desc,
        IOneInchCaller.CallDescription[] calldata calls
    )
        external
        payable
        whenNotPaused
        returns (uint256 returnAmount)
    {

        caller.makeCalls{value: msg.value}(calls);

It is calling the IOneInchCaller.makeCalls function, but nowhere is the function implementation defined.  What is going on here?

By the way, the code is pulled from here.


texts:
I followed this tutorial (https://github.com/jpmorganchase/quorum/wiki/From-Scratch) to start up Quorum with 4 nodes using istanbul consensus. The nodes can connect and blocks are being generated but I cannot add transactions as I always get "Error: invalid sender undefined" for any type of transaction I want to add (e.g. new contract creation or ether transfer).

For example if I "geth attach new-node-2/geth.ipc" into my second node and I unlock its main account so that

> personal.listWallets
[{
    accounts: [{
        address: "0x5449199af0e2c3d59b35ebabb926a2dae6e2fba4",
        url: "keystore:///home/.../Node2/new-node-2/keystore/UTC--2019-03-29T15-24-11.813787559Z--5449199af0e2c3d59b35ebabb926a2dae6e2fba4"
    }],
    status: "Unlocked",
    url: "keystore:///home/.../Node2/new-node-2/keystore/UTC--2019-03-29T15-24-11.813787559Z--5449199af0e2c3d59b35ebabb926a2dae6e2fba4"
}]

And I perform any transaction, then I get an error like so:

> eth.sendTransaction({from: '0x5449199af0e2c3d59b35ebabb926a2dae6e2fba4', to: '0x952e0ce2a4bf5e9dbbd5e186b03f760fa25d3278', value: web3.toWei(1, "ether")})
Error: invalid sender
    at web3.js:3143:20
    at web3.js:6347:15
    at web3.js:5081:36
    at <anonymous>:1:1

Note that my files are arranged:

.../Node2$ ls
genesis.json  new-node-2  node.log  nohup.out

.../Node2$ ls new-node-2/
geth
geth.ipc
keystore
nodekey
permissioned-nodes.json
static-nodes.json

.../Node2$ ls new-node-2/keystore
UTC--2019-03-29T15-24-11.813787559Z--5449199af0e2c3d59b35ebabb926a2dae6e2fba4

While all nodes share the same genesis.json, permissioned-nodes.json and static-nodes.json file. The genesis.json file being:

{
    "config": {
        "chainId": 20,
        "eip150Block": 1,
        "eip150Hash": "0x0000000000000000000000000000000000000000000000000000000000000000",
        "eip155Block": 1,
        "eip158Block": 1,
        "byzantiumBlock": 1,
        "istanbul": {
            "epoch": 30000,
            "policy": 0
        },
        "isQuorum": true
    },
    "nonce": "0x0",
    "timestamp": "0x5c9e3793",
    "extraData": "0x0000000000000000000000000000000000000000000000000000000000000000f89af854947f2fb27d5bf950b3845e6a83161afcae1cf0823e94d7427ce2ebdbfbcf9a80c628df51af118faea25894965d1690307a389e5ac9c3a2abc6972786e01f8194d2209c0a0549cf4458764bf11433a6fe4054c730b8410000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000c0",
    "gasLimit": "0xe0000000",
    "difficulty": "0x1",
    "mixHash": "0x63746963616c2062797a616e74696e65206661756c7420746f6c6572616e6365",
    "coinbase": "0x0000000000000000000000000000000000000000",
    "alloc": {
        "7f2fb27d5bf950b3845e6a83161afcae1cf0823e": {
            "balance": "0x446c3b15f9926687d2c40534fdb564000000000000"
        },
        "965d1690307a389e5ac9c3a2abc6972786e01f81": {
            "balance": "0x446c3b15f9926687d2c40534fdb564000000000000"
        },
        "d2209c0a0549cf4458764bf11433a6fe4054c730": {
            "balance": "0x446c3b15f9926687d2c40534fdb564000000000000"
        },
        "d7427ce2ebdbfbcf9a80c628df51af118faea258": {
            "balance": "0x446c3b15f9926687d2c40534fdb564000000000000"
        },
        "6f42aa5c4b9ca57d264395f4eaa8b653bb83047e": {
            "balance": "0x446c3b15f9926687d2c40534fdb564000000000000"
        },
        "5449199af0e2c3d59b35ebabb926a2dae6e2fba4": {
            "balance": "0x446c3b15f9926687d2c40534fdb564000000000000"
        },
        "5449199af0e2c3d59b35ebabb926a2dae6e2fba4": {
            "balance": "0x446c3b15f9926687d2c40534fdb564000000000000"
        },
        "6aa89d734ea689c05baa5833459e768dfb6cb54d": {
            "balance": "0x446c3b15f9926687d2c40534fdb564000000000000"
        }
    },
    "number": "0x0",
    "gasUsed": "0x0",
    "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000"
}

And all nodes are on the same  network, i.e. the following holds for all nodes:

> admin.nodeInfo.protocols.istanbul.network
20


texts: How to send multiple transactions from wallet at once?

texts:
How is this possible? Lets say i want to send 0.05 ether to 100 accounts and don't want to create one and one transactions at a time.

Is there a way to input a list of wallets that you want to send to and it does the rest?

Tried searching for a program that does this, but with no luck..

Can someone help me? Thank you! :)


texts: Reason for a transaction and 2 cancelling transactions being stuck?

texts:
I sent a transaction. Shortly after, I decided to cancel it, so made a cancel transaction (using MetaMask). After a while, since nothing was happening, I sped up the cancel transaction, i.e. sent a 2nd cancel transaction with more gas.
Now 20 minutes have passed and I see all 3 transactions in Etherscan with state "pending". All 3 show the expected (?) status:
Duplicate Nonce (found 2 other duplicate Pending Txn #1, #2 with the same `From` Account Nonce)

I also confirmed that all have the same nonce (which I assume causes the message above).
My question is why does this happen? Is it some sort of network congestion or something specific to my account? And what can I do to fix it? Do I've to keep sending cancel transactions with more gas (MetaMask doesn't seem to allow to enter a high amount from the beginning)?
Edit: I was able to solve it by retrying the original transaction. The retry transaction was marked as "failed" and the other 3 disappeared. Effectively it was cancelled. Still would like to understand this better.


texts: Creation of duplicate contract in solidity

texts: I have a contract A and values stored in it. Now, if I want to create a contract B, which uses all the values stored in contract A and do some manipulations over there, how can I implement it? i.e., how can I create a duplicate of the contract A in B?


texts: Is there a planned Ethereum protocol change which deals with upgradeable contracts?

texts: There are lots of questions asking how can you deal with contract versions with the current Ethereum protocol. Are there any plans of making protocol-level changes that are aimed to facilitate this process?


texts: why do i see input data in the transaction details when i didn't pass it as a data parameter

texts:
When I create a transaction like below

 App.contracts.Soccer.deployed().then(function(instance) {
    return instance.purchaseShoes(name, age, { from: accounts[0], value: value});
 }).then(function() {
 ...

it creates an input data in transaction details from etherscan.
Isn't  input data only created when I passed it as a data parameter? (ex: { from: accounts[0], value: value, data: 'test data' }

When I decoded the input data by converting it to utf-8 from etherscan, although it was not totally readable, I saw one of the values were the data I passed it to purchseShoes function.

So my question is, why is it creating an input data when I didn't pass it as a data param? how can I prevent it from creating it?


texts: ERC20 Token Mist 0.9.0 . Balance not showing up

texts:
I am running Ethereum Wallet and Mist 0.9.0 (released this on 24 Jul ).
ERC 20 token balance is not showing up even if Watch contact is in place.
On the other hand, I can properly see ERC 20 token balance on my wallet using ethplorer and etherscan.

All seems to be sync with the Wallet. Any thought?
Also to mention ETH balance is OK, just the ERC 20 token is missing.
Cheers!


texts: undefined contracts.contractName after compiling with solc

texts:
After compiling a smart contract with solc. I'm hitting some issues and would love some pointers for debugging/troubleshooting.

Description

    $ node
    > var solc = require("solc")
    > var src = `contract yoThere {
        string public msg;
        function yoThere() {
          msg = "Hey lol";
        }

        function greet() constant returns(string) {
          return msg;
        }
     }
     `

     > var comp = solc.compile(src)

Check contracts

> comp.contracts.yoThere
undefined

Though, if I try comp.contracts it returns the whole contract. What I would like to do is comp.contracts.yoThere.bytecode for example.

I don't know if the colon before the name :yoThere is an indication of something I've done wrong:

    > comp.contracts
    { ':yoThere':
      { assembly: { '.code': [Array], '.data': [Object] },
      // ...

Any help or pointers in the right direction would be greatly appreciated.


texts: How to change to private network in etherum wallet?

texts: How can I change to private network in the ethereum wallet. I just got two mainnet and testnet in the wallet. Appreciate your answers


texts: What do the Type Trace Addresses on the Internal Transactions Section of Etherscan mean?

texts:
I am seeking to better understand the bZx exploit by following the Internal Transaction section of the exploit transaction on Etherscan click here to view.

I am confused about what the Type Trace Addresses mean.

How do I interpret call_0_0_0_3_0_0_0 or call_0_0_0_3_0_6_0_5_0_5_0_2_2_3_7?


texts:
I've read a few other questions/answers on smart contract consensus by nodes in the network, but I still don't understand the steps.  Here's how I picture it:

Two parties might agree upon a smart contract, sign with their private keys
Nodes validate that those parties are who they say they are
Smart contract is appended to the blockchain

Let's say that the contract was a simple payout from Adam to Bob depending on the day of the week (Monday = 1 bubblecoin, Tuesday = 2 bubblecoins, etc.)

Part of the code might look something like this:

If Monday, send 1 from Adam to Bob, else
If Tuesday, send 2 from Adam to Bob, else
If Wednesday, send 3 from Adam to Bob....

My question is, if we ran the code on Wednesday, what do those nodes do? Do they check to make sure the code within the contract is the same as what every other node sees? Or do they actually run the code, get the output (here it would be 3 from Adam to Bob), and compare that OUTPUT with others in the system? If they compare output, what if the output is different between nodes?  I'm hoping that providing an example contract will help me visualize what is actually being agreed upon by the nodes.


texts: Scaling a 'factory' design approach when listing contracts

texts:
I am building a smart contract that uses a factory contract to deploy a new sub-contract (example some campaign). This campaign has a boolean flag isActive. Every time the factory deploys a campaign, it inserts its address to an array so I can have a method like getCampaigns() which returns an array of all campaign addresses.

My questions are:

If the system ends up with hundreds of thousands of campaigns, how
can getCampaigns() remain efficient? Is there something like
pagination design patterns?
An idea I have is to make a function that displays only active Campaigns. But at the factory level, the contract does not have access to the variables inside the respective Campaign. Is it possible to design something like that?

For posterity, this is the code I am using:

contract CampaignFactory {
    Campaign[] public deployedCampaigns;

    function createCampaign(string memory campaignName) public payable {
        Campaign newCampaign = (new Campaign).value(msg.value)(msg.sender, campaignName);
        deployedCampaigns.push(newCampaign);
    }

    function getCampaigns() public view returns (Campaign[] memory) {
        return deployedCampaigns;
    }

    // Is it possible to get only active campaigns using the campaignActive boolean?
    function getActiveCampaigns() public view returns (Campaign[] memory) {
        //
    }
}

contract Campaign {
    address public campaignManager;
    string public campaignName;
    bool public campaignActive;
...


texts:
Is it possible (and feasible) to have a solidity contract connect to an external api and execute a contract based on what is found?

For example betting on sports games by agreeing to a credible API before hand. If the API goes down or changes format have the ethereum refunded and self destruct the contract.


texts: Is there a way to have RPC exposed on Geth such that it can only receive signed transactions?

texts:
Is there a way I can configure my geth node RPC to only receive signed transactions?

The goal here is to run a Quorum network where the private state of a node is not visible over RPC. Though the RPC endpoint remains open to receive any inbound signed transactions.


texts: Preventing Transfer from Specific Address in ERC20 Smart Contract

texts:
We have a ERC20 contract. This contract is currently working. We want to make a change to this contract. We do not want certain addresses to transfer tokens. Is it possible to do this? How should we do it if possible
Thanks


texts:
So I have this contract and the funder can retrieve the total amounts of a specific campaign through the getFundsByAddress function. The problem is that if a campaign has more than 30 thousand founders,the contract is not able to execute the code because it would need to go through the 30 thousand times so can find all the correct addresses

In the Rinkeby nework the max a loop it can reach is 30k, after that is returning 0

How can I resolve such cases?

contract CrowdFunding {
    struct Funder {
        address addr;
        uint amount;
    }

    struct Campaign {
        address beneficiary;
        uint numFunders;
        uint amount;
        mapping (uint => Funder) funders;
    }

    uint numCampaigns;
    Campaign[] public campaigns;

    function newCampaign() public returns (uint campaignID) {
        campaignID = campaigns.length++;
        Campaign storage c = campaigns[campaignID];
        c.beneficiary = msg.sender;
    }

    function contribute(uint _campaignID, uint _amount) public {
        Campaign storage c = campaigns[_campaignID];
        c.funders[c.numFunders++] = Funder({addr: msg.sender, amount: _amount});
        c.amount += 100;
    }

    // not tested
    function getFundsByAddress() public view returns (uint[] memory) {
        Campaign storage c = campaigns[0];
        uint cont = c.numFunders;

        uint[] memory allAmount = new uint[](TotalAmountOfUser);

        uint counter = 0;

        for (uint i=0; i < cont; i++) {
           if (c.funders[counter].addr == msg.sender) {
               allAmount[amountCont] = c.funders[counter].amount;
           }
           counter++;
        }

        return allAmount;
    }
}


texts: nodejs and web3: Unhandled rejection Error: Transaction was not mined within 50 blocks, please make sure your transaction was properly send

texts:
I am trying to send ETH from one of my account to another with web3 from nodejs:

    web3.eth.personal.unlockAccount(config.mainGethAccount, config.gethPassword, function () {
        console.log("sendingTransaction: " + config.mainGethAccount);
        let obj = {
            from: config.mainGethAccount,
            to: newAccountId,
            value: web3.utils.toWei(.005, 'ether')
        };
        console.log("obj",obj);
        web3.eth.sendTransaction(obj).then(function (receipt) {
            done(newAccountId,config.userAccountGethPassword);
        });
    });

my web3 object is ok, it is able to create new account, but it crashes in .sendTransaction and ETH are actually never transferred:

sendingTransaction: 0x6c92C4201bBaFE97011C9EA9144c907Fd16F5089
[2017-08-01 03:21:46.240] [LOG]   obj { from: '0x6c92C4201bBaFE97011C9EA9144c907Fd16F5089',
  to: '0x2628fCe3675f25F94f06E1F0EE2c782be40fa6c8',
  value: '5000000000000000' }
[2017-08-01 03:22:46.040] [WARN]  Unhandled rejection Error: Transaction was not mined within 50 blocks, please make sure your transaction was properly send. Be aware that it might still be mined!
    at C:\tmp\qqq\node_modules\web3\packages\web3-core-method\src\index.js:362:45
    at tryCatcher (C:\tmp\qqq\node_modules\web3\packages\web3-core-promievent\node_modules\bluebird\js\release\util.js:16:23)
    at Promise._settlePromiseFromHandler (C:\tmp\qqq\node_modules\web3\packages\web3-core-promievent\node_modules\bluebird\js\release\promise.js:497:31)
    at Promise._settlePromise (C:\tmp\qqq\node_modules\web3\packages\web3-core-promievent\node_modules\bluebird\js\release\promise.js:555:18)
    at Promise._settlePromise0 (C:\tmp\qqq\node_modules\web3\packages\web3-core-promievent\node_modules\bluebird\js\release\promise.js:600:10)
    at Promise._settlePromises (C:\tmp\qqq\node_modules\web3\packages\web3-core-promievent\node_modules\bluebird\js\release\promise.js:679:18)
    at Async._drainQueue (C:\tmp\qqq\node_modules\web3\packages\web3-core-promievent\node_modules\bluebird\js\release\async.js:125:16)
    at Async._drainQueues (C:\tmp\qqq\node_modules\web3\packages\web3-core-promievent\node_modules\bluebird\js\release\async.js:135:10)
    at Immediate.Async.drainQueues (C:\tmp\qqq\node_modules\web3\packages\web3-core-promievent\node_modules\bluebird\js\release\async.js:16:14)
    at runCallback (timers.js:672:20)
    at tryOnImmediate (timers.js:645:5)

The most interesting thing is that it works from time to time. But is it possible to fix it?


texts: How does a miner decide how many contracts & transactions to pack into a block?

texts:
The way I understand how miners work is that they see a queue of transactions and contracts, they have a choice of picking a number of those, process them, then pack them into a block, do a PoW, then whoever finishes first wins. (please let me know if this understanding is incorrect)

This raises a question: how many contracts / transactions does a miner pack into the block? How does the miner make that decision?

There seems to be a tradeoff between speed and reward. If I want to make a ton of gas reward, then I put in a ton of transactions & contracts. But then that slows me down, and my likelihood of winning the next block is lower. If I only put a single transaction into the next block, then I can process it faster, but my reward will be low if I do win.

Does each miner then create his own optimized strategy for this? Seems like this is something I can't ever find online.

Thanks!


texts: Error: Expected import directive or contract definition

texts:
Terminal output me this error when I run:

  solc --bin --asm c1.sol

pragma solidity ^0.4.11;

contract Cm {
    uint256 a;

    function Cm() {
        a = 1;
    }
}

solc --version --> 0.3.5-371690f0/Debug-Darwin/appleclang/Interpreter

I solved the problem removing the first line. Is no longer needed to define the solidity version?


texts: Trying to use window.ethereum.request in Typescript errors out with Property 'request' does not exist on type 'EthereumProvider'

texts:
Except for one unanswered question from last November, I cannot find anything . . . .
I am revamping some typescript code (in Visual Studio) for the Metamask January change.
Previously, I was using web3.  Now I am just trying to use window.ethereum.
I cannot find a DefinitelyTyped (or any other types) file with type declarations.
I fear that this is really something simple/stupid but I'm totally at a loss.


texts: What is the best way to write into a byte variable at a predefined position?

texts:
According to the Solidity documentation one can access the byte at position k in for example a Bytes16 variable source with the following code:

pragma solidity ^0.4.8;

contract example {

 Bytes16 source=0xa9c40ddcb43ebbc83add97b8f9f361f1;

 function returnByte(uint k) returns (bytes1 a) {
    a = source[k];
    return a;
 }

}

However, as stated in the documentation, this only works for read access. What is the best way to write at a defined position k into the Bytes16 source?


texts: How can I Airdrop tokens to multiple address

texts:
I want to distribute tokens to a few thousand addresses at once. I want to know, how can I do this? My token contract is already deployed so I want to make a new contract in solidity that can interact with my deployed contract. Can someone help?

I found this code from another post on this site that I assume I can use in the new contract:

    function distributeToken(address[] addresses, uint256 _value) onlyOwner {
     for (uint i = 0; i < addresses.length; i++) {
         balances[owner] -= _value;
         balances[addresses[i]] += _value;
         Transfer(owner, addresses[i], _value);
     }
}

I am writing this contract in remix so I do not have truffle or any advance coding systems. Hope someone can help.


texts: Is an additional transaction fee possible in the ERC20 token?

texts:
Is it possible to create a token contract that pays a tiny transaction fee in the ERC20 token to a third party?

This transaction fee has nothing to do with the ETH fees which will be paid first and foremost. This is a tiny fee on every transaction paid by the receiver at the time of the payment, like a credit card transaction fee off the top of the token value coming into the receiver's wallet.

Can a tiny part of each payment be diverted to a central account?

Let's just say as an example:

1% of each payment is skimmed off the top of each payment and sent or collected into a central wallet.  Is this possible??  (this is not related to the ETH transaction fee)


texts: Trying to get child function to work - Remix won't compile parent

texts:
I am trying to create a scenario whereby a user can create a child token from the main contract (and then later on a (grand[?])child coin from that token).

I have looked up various documentation and Q&As and have cobbled together the code below. My problem is Remix will not compile the parent contract, saying that Child.sol cannot be found, even though it is two steps away from the parent. I'm fairly sure the problem is within the Child.sol contract as I've just copied and pasted the information.

pragma solidity ^0.4.21;

import "./EIP20Interface.sol";
import "../Child.sol";

contract MyTestToken is EIP20Interface {

uint256 constant private MAX_UINT256 = 2**256 - 1;
mapping (address => uint256) public balances;
mapping (address => mapping (address => uint256)) public allowed;

string public name;
uint8 public decimals;
string public symbol;

function MyTestToken(
    uint256 _initialAmount,
    string _tokenName,
    uint8 _decimalUnits,
    string _tokenSymbol
) public {
    balances[msg.sender] = _initialAmount;
    totalSupply = _initialAmount;
    name = _tokenName;
    decimals = _decimalUnits;
    symbol = _tokenSymbol;
}

function transfer(address _to, uint256 _value) public returns (bool success) {
    require(balances[msg.sender] >= _value);
    balances[msg.sender] -= _value;
    balances[_to] += _value;
    emit Transfer(msg.sender, _to, _value);
    return true;
}

function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
    uint256 allowance = allowed[_from][msg.sender];
    require(balances[_from] >= _value && allowance >= _value);
    balances[_to] += _value;
    balances[_from] -= _value;
    if (allowance < MAX_UINT256) {
        allowed[_from][msg.sender] -= _value;
    }
    emit Transfer(_from, _to, _value);
    return true;
}

function balanceOf(address _owner) public view returns (uint256 balance) {
    return balances[_owner];
}

function approve(address _spender, uint256 _value) public returns (bool success) {
    allowed[msg.sender][_spender] = _value;
    emit Approval(msg.sender, _spender, _value);
    return true;
}

function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
    return allowed[_owner][_spender];
}

mapping(bytes32 => Child) childList;

function spawnChild(bytes32 childId) {
Child current = new Child();
childList[childId] = current;
}

function callChildFunction(bytes32 childId) {
childList[childId].theChildfunction();
 }

}

pragma solidity ^0.4.21;

contract DataItem {
bytes32 key;
string value;

function DataItem(bytes32 k, string v) {
    key = k;
    value = v;
 }
}
contract DAppInterface {
mapping(bytes32 => address) public dataItems;

function addDataItem(bytes32 k, string v) external {
    dataItems[k] = new DataItem(k, v);
 }
}


texts: How to do transaction on a dapp without any wallet

texts:
I am able to do a transation in my private nework using geth console.

But I want to the transaction on a dapp without using any wallet


texts: Failed building wheel error when installing web3 using pip and Python 3.8.2

texts:
I have been trying to install web3 using the command pip install web3 but it doesn't work !!!, I have tried so many solutions but nothing works , here is the error that I have, I hope guys you can help me.
at the bigging, it gives this and then right after it just continues to give me red lines of errors
first page of error


texts: Will revert() refund all gas of the transaction or just the remaining gas?

texts:
According to the docs revert() will not consume any gas:

  Note that assert-style exceptions consume all gas available to the call, while revert-style exceptions will not consume any gas starting from the Metropolis release.

But i frequently read that revert() will refund unused gas, e.g. in this answer.

I'm thinking refunding ALL gas will open gates for DOS-attacks, so I'm assuming only unused gas will be refunded. But I would like confirmation :-)


texts:
This is probably a silly question, but I was wondering what is Mist's password for? Is it for generating private keys just like the 12-word phrase we see all the time in HD wallets?

Thanks!


texts: Meanings of a txpool.getContent() response

texts:
I'd like to understand the structure of response for txpool.getContent().

I got a following response from my geth node.

> pending: {
    '0x0000000186c96Ab17A967d7A3033db82efcA587B': { '11': [Object] },
    '0x00000004888f25bb2a792e78D5a6dF392d59e140': { '39': [Object] },
    '0x000000057c695b6Af389Ff5b7542c7e01333981A': { '13': [Object] },
    '0x000000084115EdEB2c9484b490F7AC89F8980E5F': { '12': [Object] },
    '0x000000086aD594b50486A68246D506E5DE24EBD8': {
      '12087': [Object],
      '12088': [Object],
      '12089': [Object],
      '12090': [Object],
      '12091': [Object],
      '12092': [Object],
      '12093': [Object],
      '12094': [Object],
      '12095': [Object],
      '12096': [Object],
      '12097': [Object],
      '12098': [Object],
      '12099': [Object],
      '12100': [Object],
      '12101': [Object],
      '12102': [Object]
    },
    '0x0000000A453D2De5Dd31Be7Bce57D5550a9CF964': { '16': [Object] },
    '0x0000000Ae22EDb6fa815aBF4F32E4d4c3CD4944A': { '11': [Object] },
    '0x0000000Ba1365f06809Ebc4A9086913696810268': { '19': [Object] },
    '0x0000000FA550De25e3AEBE8CB0f06a803CEE8f81': { '16': [Object] },
    .........

So I don't know the meaning of the number, for example '11' in first line of pending object which is included above response.

Someone, could you tell me the meaning.

And If anyone knows, please tell me exact structure of response for txpool.getContent().

I already have read this document.

However, it does not provide details such as the meaning of the number mentioned above.

And please also tell me the details of txpool.getInspection() response.

My development environment is as follows:

IDE: IntelliJ(2019.3.3)
node.js: ver 13.6
web3.js: ver 2.0.0-alpha.1
web3-eth-txpool: 1.0.0-beta.55
geth: ver 1.9.11-stable


texts: "No data is deployed on the contact address!" Token issue

texts:
Here is my code:

pragma solidity 0.4.11;

contract MyToken {
string public name;
string public symbol;
uint8 public decimals;
string public standard = 'RNTLcoin 0.1';
uint256 public totalSupply;

mapping (address => uint256) public balanceOf;

event Transfer(address indexed from, address indexed to, uint256 value);

function MyToken(
    uint256 initialSupply,
    string tokenName,
    uint8 decimalUnits,
    string tokenSymbol){
    balanceOf[msg.sender] = initialSupply;
    name = tokenName;
    symbol = tokenSymbol;
    decimals = decimalUnits;
    }

function transfer(address _to, uint256 _value) {
    if (balanceOf[msg.sender] < _value) throw;           //
    if (balanceOf[_to] + _value < balanceOf[_to]) throw; //
    balanceOf[msg.sender] -= _value;                     //
    balanceOf[_to] += _value;                            //

} }

I am running a private blockchain with Gethdev and attaching with the lastest Ethereum Wallet. However, it doesn't display any tokens being created even though the transaction is mined. I've tried using the maximum gas, minimum gas and required gas and still it doesn't work. Can anyone explain why this is happening? Thank you very much for your help.


texts: Delegatecall require statement does not cause an abortion in any way

texts:
This is a sequel to a previous question of mine.

I want to implement a validation function (e.g. for passwords) within a central contract, that could be used by other contracts. It is important to notice, that this validation also considered the address of the caller. Therefore it needs to be called by delegatecall in order to access the actual caller through msg.sender. Since I cannot receive values when calling a function by delegatecall call (see my previous request), my new attempt is to abort processing by using several require statements within the validation function. Unfortunately, this does not seem to work, even if I force a require abortion.

contract Caller {

 function doSomething(address _callee, string _text) public {
   _callee.delegatecall(
                     bytes4(keccak256("validate(string)")), _text));

 /* further process if text is valid */
 }
}

contract Callee {

 function validate(string _text) public view {
  /* validity check */
  require(false);
 }
}

Even in the above example code, where I force an abortion, doSomething finished successfully. Any hint?


texts:
According to Etherscan the last mined block was block 2933931.

However, my node is stuck at block 2933993.

On their website they are announcing the following: "Node Resynch in progress. Indexing will restart once the synch has been completed."

Does anybody has any idea what is going on with Ropsten?


texts: Getting multiple values in single Oraclize query

texts:
Is it possible to get multiple values in single Oraclize query?

contract CheckBet is usingOraclize {

struct Weather {
    uint curr_temperature;
    uint high_temperature;
    uint low_temperature;
}
Weather weather;

/// Event for debugging
event Log(string text);

function CheckBet() {
    get_weather_status();
}

function get_weather_status() payable{
    Log("Oraclize query was sent, waiting for the answer..");
    (oraclize_query("URL","json(http://samples.openweathermap.org/data/2.5/weather?q=Lond`on,uk&appid=b6907d289e10d714a6e88b30761fae22).main.temp_min"));
}

//callback function for Oraclize
function __callback(bytes32 _myid, string _result) {
    require (msg.sender == oraclize_cbAddress());
    Log(_result);
    weather.low_temperature = parseInt(_result);
}

In function get_weather_status, I'm getting min. temp. I want temp_max, curr_temp too.

Is it possible in single Oraclize query?

JSON FILE

{
  "main": {
   "temp":280.32,
   "pressure":1012,
   "humidity":81,
   "temp_min":279.15,
   "temp_max":281.15
  }
}


texts: Deploying contracts on geth returns {"jsonrpc":"2.0","error":{"code":-32600,"message":"EOF"}}

texts:
I'm trying to connect geth with truffle to deploy my contracts to my testrpc. When I run truffle deploy it's running but when I do http://localhost:8545/ it's throwing

{"jsonrpc":"2.0","error":{"code":-32600,"message":"EOF"}}

as JSON is invalid. My geth is working properly and I'm using same ports in geth and truffle. When I do

curl -X POST --data '{"jsonrpc":"2.0","method":"eth_getBalance","params":["0x822a9cba371309c14e2235057fc561156212cd94", "860"],"id":1}' http://localhost:8545

it throws

{"jsonrpc":"2.0","id":1,"result":"\u003cnil\u003e"}

which I am unable to understand. Where am I going wrong?
And is pudding necessary to connect geth and truffle?

I tried this link but no luck
Deploying contracts on geth returns Error: connect ECONNREFUSED 127.0.0.1:8545


texts: How to Initialize two items with item 1 and 2 which is an array

texts:
I was given this assignment to initialize an array with 2 items but when I initialized them i had an error that said "invalid implicit conversion from int const_1 to uint256[]memory req".
Below are the full codes. EMPHASIS LAID ON THE STRUCT ITEM AND ITEM INITIALIZATION
pragma solidity ^0.4.17;
contract Auction {

    // Data
    //Structure to hold details of the item
    struct Item {
        uint itemId; // id of the item
        uint[] itemTokens;  //tokens bid in favor of the item

    }

   //Structure to hold the details of a persons
    struct Person {
        uint remainingTokens; // tokens remaining with bidder
        uint personId; // it serves as tokenId as well
        address addr;//address of the bidder
    }

    mapping(address => Person) tokenDetails; //address to person
    Person [4] bidders;//Array containing 4 person objects

    Item [3] public items;//Array containing 3 item objects
    address[3] public winners;//Array for address of winners
    address public beneficiary;//owner of the smart contract

    uint bidderCount=0;//counter

    //functions

    function Auction() public payable{    //constructor

        //Part 1 Task 1. Initialize beneficiary with address of smart contract’s owner
        //Hint. In the constructor,"msg.sender" is the address of the owner.
        // ** Start code here. 1 line approximately. **/
         beneficiary = msg.sender;
          //** End code here. **/
        uint[] memory emptyArray;
        items[0] = Item({itemId:0,itemTokens:emptyArray});

        //Part 1 Task 2. Initialize two items with at index 1 and 2.
        // ** Start code here. 2 lines approximately. **/
        items[1] = Item({itemId:1, itemTokens:1});
        items[2] = Item({itemId:2, itemTokens:2});
        //** End code here**/
    }


texts: How to call Solidity contract function in node.js only after the contract has been deployed?

texts:
Would like to call the deployedContract.changeFirstName function only after the deployedContract is complete because deployedContract is an asynchronous function. What would be the best way to do that?

    //creating a new instance of contract, this is an async call - hence the need to wait. Otherwise VM-ware invalid op$ deployedContract = IDLedgerContract.new([],{data: byteCode, from: web3.eth.accounts[0], gas: 4700000},
    (err, contract) =>
    {
    if (contract.address !== undefined)
            console.log('Sample contract address has been defined: ' + contract.address)

    } );

    //deployedContract.changeFirstName('test', {from: web3.eth.accounts[0]}) //This needs to happen after the deployedContract has been deployed


texts:
I want to know the structure of storage trie and its data structure in leveldb, and I read solidity storage.

I still have questions?

In the yellow paper, it says that storage root is a mapping between 256-bit integer and 256-bit integer, is this key value pair store in leveldb?
If we want to store one value V in the storage trie of one contract. Following
solidity storage, I count the key K  for V, and insert V using K in the storage trie (just like K is the account address and V is the account state in the state trie). Then update the storage root just like state trie. Am I right?
If question 1 is right, what's the real key we use to store V in leveldb, is it K or K and something after SHA3? How can we get the parent hash of some leaf value nodes, just use SHA3(value1, value2, ...)?


texts: What does Solidity's "call" function mean?

texts:
address nameReg = 0x72ba7d8e73fe8eb666ea66babc8116a41bfb10e2;
nameReg.call("register", "MyName"); //1
nameReg.call(bytes4(sha3("fun(uint256)")), a); //2
if(!nameReg.call.value(10)){throw;} //3

Here it says,

  Furthermore, to interface with contracts that do not adhere to the
  ABI, the function call is provided which takes an arbitrary number of
  arguments of any type. These arguments are padded to 32 bytes and
  concatenated. One exception is the case where the first argument is
  encoded to exactly four bytes. In this case, it is not padded to allow
  the use of function signatures here.

Are 1 and 2 legal?
Does it mean that 2  is illegal?
What does the 3 mean?


texts: Using etherscan to track the status of incomming transactions, free version?

texts:
I plan to start to accept Ethereum and some tokens based on it, on a website. The volume would be, I think, at most 10-50 payments a day, at most. And I want to allow a user to know the status of a payment in an automatic manner. For this I'll be sending Http request to the API of etherscan.io every, say, 30-60 seconds.

I'm aware of the limit of etherscan which is over 5 requests per seconds. My volume, even if it was 1 req/sec, would be way less than that, that is, it'd work fine.

Are there any downsides or thing to pay attention to that I've overlooked?


texts:
We're using some of the lower level functions in the go-ethereum project (not geth). We've implemented our own peer protocols and are wondering how we can unit test these.

For context, we set up a P2P server and it bootstraps to other nodes, creating Peer objects as the handshakes are completed. This kicks off the protocol code:

func Run(p *p2p.Peer, rw p2p.MsgReadWriter) error {
    // Protocol code here
}

The specifics of our protocol aren't important, but it's essentially a request-reply handshake (similar to ping-pong). We'd like to test for things like timeouts, whether the protocol sends a "ping" request, whether it responds with a "pong" request, and that the peer connection is disconnected if a bad message is received.

I've looked at protocoltester.go and peer_test.go for inspiration, but both of these approaches would require duplicate massive amounts of private functions to get them to work.

Finally, our protocol code works. We're just looking to write unit tests to ensure that it continues to work.
Any ideas?


texts: How to find the first block after given timepoint in solidity?

texts:
function firstBlockAfter (uint timepoint) returns (uint) {
    // returns the first block number after timepoint
}

Is there any solution except iterating the latest 256 blocks?


texts:
How to create a stable coin with an ERC20 token contract ? Does it require contract to be modified ?
Are there some good practices or standards ?


texts: Quorum: "read error invalid character 'P' looking for beginning of value" on private transaction

texts:
Quorum over Ubuntu 16.04, Geth 1.7.2-stable.

Quorum is installed and it passes the tests. 3 nodes (all roles enabled) with their corresponding constellations. Tested both over 3 local docker containers and over 3 remote virtual machines.

Ethereum regular transactions work properly. But, when trying to perform private transactions by adding the privateFor field, I get:

  TRACE[02-08|16:37:15] Dial task done                           task="discovery lookup"

  TRACE[02-08|16:37:15] New dial task                            task="discovery lookup"

  INFO [02-08|16:37:18] sending private tx                       data= privatefrom= privatefor="[Hniwqqpw1SE0BDpxAhp7w0Q6NLMCh4x77xA83iM6amk=]"

  DEBUG[02-08|16:37:18] read error invalid character 'P' looking for beginning of value

  INFO [02-08|16:37:18] sent private tx                          data= privatefrom= privatefor="[Hniwqqpw1SE0BDpxAhp7w0Q6NLMCh4x77xA83iM6amk=]"

That was the simplest attempt. I have also tried to upload an smart contract, etc.

The error comes from line 97 of https://github.com/jpmorganchase/quorum/blob/master/private/constellation/node.go (c.httpClient.Do(req)) and the 'P' character is the 'P' from 'POST', the method name. GET method causes a invalid character 'G'.

It looks a little weird to me. It is probably related to my configuration and not Quorum itself, but I have checked all the steps and some existing examples and rebuilt Quorum after inserting more log messages and I cannot find the problem.

Any suggestion about my issue?

Thank you in advance.


texts: What does "0x0 Transaction mined but execution failed" mean when attempting to deploy via Remix on Rinkeby?

texts:
I am attempting to deploy a test contract on Rinkeby using Remix IDE and the MetaMask extension in chrome. However when I try to execute the contract I receive this message in the status section: "0x0 Transaction mined but execution failed".

What does this mean and what could be causing such a problem?

I appreciate any ideas on how to fix this error. Thank you.


texts: Can I monitor contract's activity on any explorer?

texts: Is there any way I can use a blockchain explorer or similar tool to find out how much activity there is on addresses for specific ethereum based services (Digix, Augur etc. pp.)?


texts: Transaction to smart contract shows 'invalid address' error message

texts:
I'm simply trying to transfer ETHER to a smart contract deployed on testrpc:

web3.eth.sendTransaction({to: "0xdbf5c15f21ae03f0e33c9058d3823d4e74a35be3", value: web3.toWei(100, "ether")});

Quering information from the contract works fine. Thus the address should be alright. However whenever I execute sendTransaction, I get this error:

Any suggestions what I can try to make this work?


texts: Does Proof-of-Stake mining also process contracts?

texts: I've read that Proof-of-Stake (POS) mining 'secures the blockchain' but does it also process contracts and collect gas?


texts: Exploring Ethereum's state trie with golang

texts:
Exploring Ethereum's state trie with Node.js

It is a nice article to explore ethereum internal storage, but the code is Node.js.
Does anyone have a golang version?


texts: There been a couple of questions on bytes32 to string in solidity itself.  What's the best way to convert a solidity bytes32 return value to a string in JS?


texts: Display Data from Another Contract in Solidity

texts:
The code compiles well.   But it gives the following error, when event LogData is activated.   LogAddress works well.  Do I have to set up explicit getters for the State Variables?

  transact to browser/Test.sol:Factory.getContract errored: VM error:
  invalid opcode.   The constructor should be payable if you send value.
    The execution might have thrown.    Debug the transaction to get more
  information.

pragma solidity ^0.4.15;

contract TestContract {

    uint public iD;
    bytes32 public name;
    function setAttr(uint _id, bytes32 _name) {
        iD = _id;
        name = _name;
    }
}

contract Factory {

    TestContract myTest;
    address contractAddress;
    function Factory () {
        myTest = new TestContract();
        myTest.setAttr(100,"0x111");
        contractAddress = address(myTest);
    }

    event LogData(uint _mydata, bytes32 _name);
    event LogAddress(address _add);
    function getContract() {
        myTest = TestContract(contractAddress);
        LogAddress(contractAddress);
        LogData(myTest.iD(), myTest.name());
    }

}


texts: How do nodes agree on which transactions to include in the block?

texts: I know gas prices and nonce are used. But what if different clients use different ordering of transactions? How do thousands of nodes agree on exact transactions to be included in the next block? And how does a transaction get propagated through network at all? How can you have such consistency?


texts:
16GB Linux, 512 GB SSD, mainly started for RPC purposes only. No mining activity.

geth --datadir ./data --syncmode fast console --rpc --rpcport 8545 --rpcaddr "0.0.0.0" --rpccorsdomain "*" --rpcapi "db,eth,net,web3,personal" --etherbase "0x..Censored"

The node was synced after 3 ~ 4 days.

But then from time to time, it will get out of sync. Can't catchup with the mainnet.

Sometimes it can be few thousands block behind. Even when it is left idle (no RPC calls)

May I know if there is a way to improve?

> eth.syncing
{
  currentBlock: 7525381,
  highestBlock: 7525470,
  knownStates: 376823561,
  pulledStates: 376819512,
  startingBlock: 7422751
}
> INFO [04-08|05:04:52.886] Imported new state entries count=477  elapsed=3.605ms   processed=376819989 pending=3914  retry=0   duplicate=8198 unexpected=100391


texts: Is there a reason why my blockchain download stalls out at block ~2,429,000

texts: I have downloaded the latest stable release of the ethereum wallet for windows. I installed everything and now I am just downloading. (I have repeated this process twice and the same issue has occured), while downloading the blockchain, my download seems to stop or slow down to only a few blocks per minute at the ~2,429,000 block. Any idea why this is happening. I have tried erasing the AppData of the blockchain and using a completely fresh install of both ethereum wallet and the blockchain.


texts: Abi encode / decode using strings instead of bytes

texts:
For some reason beyond my control, I need to store encoded data in a string variable.

I know abi.encode and abi.decode usually work on bytes memory but I also believe that string memory can be casted to bytes memory.

Here is an example contract I use to debug in remix:

pragma solidity ^0.5.0;

contract Test
{
    function encode(uint256 a, string calldata b) external pure returns(string memory)
    {
        return string(abi.encode(a, b));
    }
    function decode(string calldata a) external pure returns(uint256, string memory)
    {
        return abi.decode(bytes(a), (uint256, string));
    }
}

It works great with some values. For example encode(42, "test") returns

\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000*\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000@\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0004test\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000

which can then be decoded back to 42, "test".

However, for some values, such as 255, "test", then I get a revert when trying to decode the encoded string.

Any idea how to solve that ? Is their no other way then to use bytes instead of string ?


texts: Jaxx Wallet QR Code shows IBAN and etherscan shows 0 balance

texts:
When I scan the QR code from the Jaxx Etherium wallet I get

iban:XE482ECP16CJCBQHZ7S844BEK8K1SDOX0HH

but it shows my address as

0x1488e397bc44c56d801a6e96217554a0e310ecb5

in the app it shows I have 0.59755900 ETH

but on etherscan that address has 0 ETH

https://etherscan.io/address/0x1488e397bc44c56d801a6e96217554a0e310ecb5

My questions are, why doesn't the QR code scan to my address and secondly why does etherscan.io show my balance as 0 when jaxx says I have 0.59755900 ETH??


texts:
Should I validate msg.data.length for methods that may change storage?

http://securify.ch/ recommends this but I can't find any mentions/explanations elsewhere.

Shouldn't this only be a problem, when I typecast values, e.g. uint8 to uint256 or so?


texts: How does Casper solve the "Nothing at Stake" issue?

texts:
One of the criticisms of proof of stake is that stakers can vote for multiple blockchain forks with only a trivial cost. I believe NXT solves this by not giving out a mining reward, so that the reduced security of voting for multiple blockchain tips is sufficient deterrent. It is my understanding that Ethereum has a block reward.
How then does Casper solve the "Nothing at Stake" issue?


texts:
I currently have the following loop (some stuff left out)

mapping (address => uint) pendingWithdrawals;

function example () private{
    address[] tempList = List;
    for(uint k = 0; k < tempList.length; k++){
            Struct storage val = mapping[tempList[k]];
            pendingWithdrawals[tempList[k]] = (val.value);
    }
}

In this situation, I am looping over a list which I created locally to save on gas and calling the mapping pendingWithdrawals within the loop. But how can I achieve the same goal with the mapping? Since you can't assign to mappings I can't create a local mapping, write to the local mapping and update the new global mapping once finished. Which makes this for loop very costly in terms of having to call the storage over every iteration within the loop.


texts:
I'm running the following command to get the toml configuration file:

geth --datadir ./chain --nat extip:182.168.1.2 dumpconfig echo > config.toml

But when I start get with the config.toml

geth --config config.toml console

I get the error.

Fatal: config.toml, line 35: (p2p.Config.NAT) cannot unmarshal TOML array into nat.Interface (need slice)

I think it's coming from --nat extip:182.168.1.2, because without it is working.

Here the relevant part of config.toml.

NAT = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 182, 168, 1, 2]

Any idea how to get past this issue ?


texts: Can a contract keep track of sent transactions?

texts:
Let's say I have a contract with a "withdraw" function.
Now someone calls this withdraw function, resulting in the contract doing something like receiverAddress.transfer(amount).

Now I would like to keep a list of all outgoing transactions in the contract. I understand the outgoing transaction is actually just a part of the calling transaction, so there is not yet a transactionID to store in the contract. Correct?

What options does my contract have if i want to keep a list of all performed transactions? I was envisioning a list of transactionIDs, but as far as I understand this is not possible.


texts: Why do my events not emit the correct value?

texts:
When testing a contract with Truffle, I have found that the variables that are emitted by the event do not match the values that are passed into the event emission. Why does the event not return the exact value that is passed into it?

For example:

event ExampleEvent(string indexed myString);

function eventTest() public {
    string memory strTest = "Hello, world!";
    emit ExampleEvent(strTest);
}

When eventTest() is called, the event emits 0xb6e16d27ac5ab427a7f68900ac5559ce272dc6c37c82b3e052246c82244c50e4, instead of "Hello, world!". Why is this the case?


texts: Interacting with contracts on Solidity 0.4.* and Solidity 0.5.* in Truffle v5

texts:
I have a big contract (A) that is built using Solidity 0.4.25.
I also want to build several contracts (B) that will talk to (A), but they will be built using Solidity 0.5.*.

As I understand, I will not be able to compile and test contracts (A) and (B) on ganache-cli. I have to change contract (A) to Solidity 0.5.* to make it work (I use truffle v5).

If I understand it correctly, I can only interact with contracts that use 0.4.* using an interface and those contracts have to be deployed on a test/main network?


texts: Deploy instance of smart contract via UI with parameters, then interact with that contract via UI

texts:
Is it possible to for a user to interact with a newly deployed instance of a contract with different parameters with the same ABI/UI

See example below;

User adds to inputs via UI (e.g 10, 0x123451234512345) and clicks submit, this prompts metamask, user deploys contract via metamask.

pragma solidity 0.4.18;

// User adds two parameters;
// Stake
// Opponent
contract Betslip {

    uint stake;
    address opponent;

    function Betslip (uint _stake, address _opponent) public {
        stake = _stake;
        opponent = _opponent;
    }

    // Rest of contract methods

}

newly deployed contract address: 0x123456789123456789123456789

User navigates to new UI and enters the newly deployed contract address (0x123456789123456789123456789) in the provided input, submits and can now use the same ABI to interact with the new contract.


texts: is it possible to add whitelist of contract in self mainnet node?

texts:
I am working in a company write games on eth mainnet and maintenance a eth node(geth) not using infura.io.

My boss require me our eth node just can deal with our contract, so is it possible to do it? I search google 'geth contract whitelist' but no any result I want.


texts: Do I need more than my public and private key to sweep my paper wallet?

texts:
I have Ether funds currently held by an exchange which I
wish to withdraw to a MyEther Paper Wallet for safety. In
the creation process ID and keyfiles are generated which I
am urged to record. At some future date I will sweep the
Ether from my paper wallet back to the exchange.

My (noob) question is do I need anything other than my
public and private keys (as shown on the printed paper
wallet) to achieve this. Will I need the aforementioned ID
and keyfiles? I intend to rely solely on the safety of a
paper wallet kept securely in multi locations.This is my first foray into cryptocurrency.


texts:
I have this simple contract where I want to save struct B with the name "poop" and an empty array of type struct A in the list wow.
contract Test {
    struct A {
        uint balls;
    }

    struct B {
        string name;
        A[] As;
    }

    B[] public wow;

    function create(uint _n) public {
        B memory lol;
        lol.name = "poop";
        wow.push(lol);
    }
}

When compiling, I get UnimplementedFeatureError: Copying of type struct Test.A memory[] memory to storage not yet supported.


texts: Cannot create instance in contract because of overloaded constructor

texts:
I have two contracts, TokenContract and DynamicContract. The latter is created dynamically.

I want to call a function of DynamicContract from TokenContract (receiveApproval). According to this question, what I need to do is this:

function ApproveAndCall(address dynContAddress, uint value){
  DynamicContract dynamicContractInstance = DynamicContract(dynContAddress);
  dynamicContractInstance.foo();

  return true;
}

I have import "./DynamicContract.sol"; at the beginning of my TokenContract.

The thing is, I already have a constructor for DynamicContract and it takes a bunch of parameters. So I get a compilation error stating I don't have the right parameters.

I also tried using simply DynamicContract(dynContAddress).foo() but I get Member "foo" not found or not visible after argument-dependent lookup in address

EDIT:
Maybe I should use function ApproveAndCall(DynamicContract dynContAddress, ...){} instead of function ApproveAndCall(address dynContAddress, ...) if I want to use dynContAddress.foo(){}? What's the difference?

I think the problem might come from the fact that both contract call functions of the other, so both have import "./OtherContract.sol". Since one has to compile before the other there might be a problem (Solidity isn't as flexible as some other languages).

Could it be the problem? Then how could I solve it? (I don't think the contract is over complicated, I just want to pay for functions in token and transfer them to the address they belong to).

EDIT 2:
Actually I don't think that's the problem because when running truffle compile, I get Compiling .\contracts\DynamicContract.sol...and Compiling .\contracts\Factory.sol... before Compiling .\contracts\Token.sol... that gives the error. (member not found or not visible ...)


texts: Is it possible to call another contract from a contract maintaining the msg.sender of the original caller?

texts:
Imagine that Alice calls a contract method C1 and that method calls another method in contract C2.

Regularly msg.sender equals the Alice Account in the C1 method. And  msg.sender equals the C1 contract address in the C2 method.

I would like to know if it is possible to call C2 in such a way that msg.sender is still the Alice address instead of C1 address. And that C2 can access C2's state variables.

I have tried to use delegatecall and callcode, but those functions seems that C2 has only access to the C1 state but not the C2 state. I guess that those calls are more prepared for libraries.

It would be good to have an example of this call.


texts: If I were to fork my private Proof of Authority chain can I revert without pruning a block with corrupted data and subsequently all successor blocks which do have complete data and if so how can I make the chain continue mining on the temporarily shorter block list until the forked section grows?


texts: Unable to create, sign, and broadcast eth transaction on ropsten with ledger nano s

texts:
I am unable to successfully sign and broadcast an eth transaction. My code is below.

Sign transaction code:

const getTransport = () => TransportU2F.create()
const eth = new AppEth(transport)

const rawTxData = {
  'nonce': '0x01',
  'gasPrice': '0x2cb417800',
  'gasLimit': '0x5208',
  'from': '0x4422D3c22Ec36739713636eca288Ca8ddB0106E9',
  'to': '0x4203b1F04e88C0E8B1b54b0e38065a3d006283D3',
  'value': '0x5af3107a4000',
  'chainId': '3',
  'v': '0x03',
  'r': '0x00',
  's': '0x00'
}

const tx = new EthereumTx(rawTxData)

const result = await eth.signTransaction(
  "44'/60'/0'/2",
  tx.serialize().toString('hex')
)

tx.v = Buffer.from(result.v, 'hex')
tx.r = Buffer.from(result.r, 'hex')
tx.s = Buffer.from(result.s, 'hex')

return tx

Broadcast transaction code:

const signedTransaction = `0x${signedTx.serialize().toString("hex")}`

web3.eth.sendSignedTransaction(signedTransaction)
.on('transactionHash', function(hash) {
  console.log('Transaction hash: ' + hash)
  callback(hash)
})
.on('confirmation', function(confirmationNumber, receipt) {
  console.log('Confirmation number: ' + confirmationNumber)
})
.on('receipt', function(receipt) {
  console.log('Receipt: ' + receipt)
})
.on('error', console.error)

The transaction is sent out smoothly, but on ropsten.etherscan.io the transaction comes up as:

Sorry, we are unable to locate this Transaction Hash.

Any ideas why this is happening? Any help is much appreciated! I have been stuck on this for days.

Also, are there any full examples out there of creating a raw eth transaction, signing it with the ledger, and broadcasting it to the Ethereum network? I am unable to find any in the ledger documentation or anywhere on github.


texts: Executing a Smart Contract in a Mobile App

texts:
I am new to the world of Blockchain and Ethereum has indeed become a second name for open source Blockchain.

Right now I am trying to grasp the concepts and there are really many wonderful blogs but I could not find a thread which explains the following problem :

Suppose, I as a developer want to make a smart contract on any blockchain(say Ethereum for now),now the execution, processing of that smart contract in Ethereum is done in its blockchain, which might have APIs exposing it.

So if say, I have an hybrid app and want my app users to see and modify the blockchain through the smart contract then what all things will the developer has to consider in mind while developing that kind of app.

And in general I want a detailed explanation on how can the smart contract executed on a web app or any app. This explanation might also be useful for many looking for answers in this field.


texts: Do file names need to be UTF-8 for solc to be able to compile them?

texts:
I combed through the Using the compiler section in the Solidity documentation, but I couldn't find an answer for my question.
Do file names need to be valid UTF-8 for solc to be able to compile them?


texts: Token pegged to the average return of ex top 10 cryptos

texts:
summer is coming up and I'm taking some of my vacation time to develop a crypto currency of my own. I'm looking to create a token that has a return pegged the average of for example the top 10 cryptocurrencies, first of all is this possible? And if how would go ahead coding a token like this?
Thank you in advance, and take care!


texts: how to verify a contract using truffle-plugin-verify

texts:
I'm trying to verify a simple contract. The contract is already deployed on the Ropsten network.
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";

contract Tress is ERC20, AccessControl {
    bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
    bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE");

    constructor() public ERC20("TRESS", "TRS") {
        // Grant the contract deployer the default admin role: it will be able
        // to grant and revoke any roles
        _setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
    }

    function mint(address to, uint256 amount) public {
        require(hasRole(MINTER_ROLE, msg.sender), "Caller is not a minter");
        _mint(to, amount);
    }

    function burn(address from, uint256 amount) public {
        require(hasRole(BURNER_ROLE, msg.sender), "Caller is not a burner");
        _burn(from, amount);
    }
}

But it doesn't work for me. It throws me the following error.

I appreciate any help


texts:
I want to create a smart contract that contains the public key of a party (the key is generated outside the blockchain) and  contains  a function to verify signed data.
How can we implement this function in solidity?
I took a look to ecrecover but I think it need an ethereum address instead of a public key.

[UPDATE] : the public key isn't related to any ethereum address.


texts:
Hey guys I had a problem with my return function

here's my smart contract :

pragma solidity >=0.4.0 <0.7.0;

contract NewHello{

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

modifier onlyOwner (){
    if(msg.sender != owner){
        require(msg.sender == newOwner);
    }
    else{
        require(msg.sender == owner);
        _;
    }
}

struct user{
    string name;
    string surname;
    uint age;
}

 event infoChanged(
    string name,
    string surname,
    uint age
);

mapping(address => user) public users; // contains a user for every address

function setUser(string memory name,string memory surname,uint age) public payable{
    users[msg.sender] = user(name,surname,age);
    emit infoChanged(name,surname,age);
}

function setUserbyAdmin(address _address,string memory name,string memory surname,uint age) public  onlyOwner {
    users[_address] = user(name,surname,age);
    emit infoChanged(name,surname,age);
}

function getUser(address _address) public view returns(string memory name , string memory surname, uint age)  {

    return (users[_address].name,users[_address].surname,users[_address].age);
}

}

and my web3.js code is here :

var getUserFunction = function(cb,_contractAddress = contractAddress, _jsonFile = JSONFile){
    var abi = JSONFile.abi;

    var contract = new web3.eth.Contract(abi,_contractAddress);

    contract.methods.getUser().call().then(function(data){
        cb(undefined,data);
    }).catch(function(err){
        cb(err,undefined)
    });

}

module.exports.getUser = getUserFunction;

and I call my function at orchestra.js. here's the code :

API.getUser(function(err,_data1,_data2,_data3){
    data1= _data1;
    data2=_data2;
    data3=_data3
    if(err){
        console.log(err);
        return;
    }
    console.log(data1,data2,data3);
}, '0xDeDbB36387f42FEB764056d1D52391F0A6B15D04',//contractaddress
require('./build/contracts/NewHello.json'));

I see 2 errors on my terminal

{ Error: types/values length mismatch (count={"types":1,"values":0}, value={"types":[{"name":"_address","type":"address"}],"values":[]}, version=4.0.29)

anyone can help me please ?


texts:
pragma solidity ^0.4.16;

interface token {
    function mintToken(address receiver, uint amount);
}

contract Owned {

    address owner;

    /*this function is executed at initialization and sets the owner of the contract */
    function owned() { owner = msg.sender; }

    modifier onlyOwner() {
        require(msg.sender == owner);
        _;
    }
}

contract Selfdestroy is Owned {

    /* Function to recover the funds on the contract */
    function Destroy() onlyOwner() {
        selfdestruct(owner);
    }

}

contract Crowdsale is Owned,Selfdestroy {
    address public beneficiary;
    uint public fundingGoal;
    uint public amountRaised;
    uint public deadline;
    uint public price;
    token public tokenReward;
    mapping(address => uint256) public balanceOf;
    bool crowdsaleClosed = false;

    event GoalReached(address recipient, uint totalAmountRaised);
    event FundTransfer(address backer, uint amount, bool isContribution);

    /**
     * Constrctor function
     *
     * Setup the owner
     */
    function Crowdsale(
        address ifSuccessfulSendTo,
        uint fundingGoalInEthers,
        uint durationInMinutes,
        uint etherCostOfEachToken,
        address addressOfTokenUsedAsReward
    ) {
        beneficiary = ifSuccessfulSendTo;
        fundingGoal = fundingGoalInEthers * 1 ether;
        deadline = now + durationInMinutes * 1 minutes;
        price = etherCostOfEachToken;
        tokenReward = token(addressOfTokenUsedAsReward);
    }

    /**
     * Fallback function
     *
     * The function without name is the default function that is called whenever anyone sends funds to a contract
     */
    function () payable {
        uint amount = msg.value;
        balanceOf[msg.sender] += amount;
        amountRaised += amount;
        tokenReward.mintToken(msg.sender, amount / price);
        FundTransfer(msg.sender, amount, true);
    }

    /**
     * Withdraw the funds
     */
    function OwnerWithdrawal() onlyOwner {
     beneficiary.transfer(amountRaised);
    }

}

I edit the function OwnerWithdrawal to withdraw eth from contract , but it's can't execute on second time. Is there any way to execute many time I want?


texts: Build something similar with Ethereum for what I have with Bitcoin

texts:
This is what I have and need with Bitcoin:
I use Blockcypher.com payment forward service,which generates a new unique Bitcoin address for a new members payment.
When I get paid with Bitcoin, Blockcypher.com makes a callback POST to my website URL identifying the member.
From there I handle some logic in my VPS.

How could I build something similar with Blockcypher Ethereum service?
Generate unique address for customer.
Making a POST callback to my server when a payment has been received.


texts: Check balance without waiting for blockchain to sync using Mist

texts:
I did not use my wallet for a few months and when I tried to transfer my ether I could not reliably see the balance. The system is taking a long time to update.

Is there anyway to avoid a client update for a MIST wallet and have some kind of wallet online which avoids a client download?


texts: How can I prove `sha256^1000000000(X) = Y` for a verifier that can't perform that much computations?

texts:
Suppose, for example, I want to write an Ethereum contract that pays 1 ETH for whoever gives me the right answer to sha256^1000000000("good boy"). That amount of computation would be much higher than Ethereum's gas limit, so, I need a way to prove sha256^1000000000("good boy") = Y without needing that much computing power on the verifier's side.

How can that be done?

(That is an weaker version of my earlier question, that didn't get good answers. Hopefully this problem is simpler?)


texts: web3.eth.getAccounts() : Cannot read property 'map' of undefined

texts:
const HDWalletProvider = require('truffle-hdwallet-provider');
 const Web3 = require('web3');
 const provider = new HDWalletProvider( 'passphrase', 'rinkeby.infura.io/v3/mytoken' );
 const web3 = new Web3(provider);
 const deploy = async () =>{ const accounts = await web3.eth.getAccounts(); } deploy();

gives

  TypeError:Cannot read property 'map' of undefined at
  GetAccountsMethod.afterExecution

versions used:

 "solc": "^0.4.24",
 "truffle-hdwallet-provider": "^1.0.4",
 "web3": "^1.0.0-beta.46"

any solution woud be grateful. Thanks in advance.


texts: limit number of token in one address ethereum

texts:
Is it possible to create a token that each ethereum address can not exceed 100,000 token.

If the token amount exceed the 100,000, it will "overflow" and retrieve the transaction.

Thank you


texts: How does a wallet integrate dex protocols?

texts:
How can a standard wallet with no exchange feature integrate dex protocols that allow users to swap ETH and ERC20 tokens within the app?

I know there are some dex protocols out there but which protocol allows developers to integrate the dex feature easily and reliably?


texts: what is the role of relayer in 0x protocol?

texts: I understand that 0x protocol allows orders to be transmitted across off chain channel to reach large audience and potential buyers/sellers. However, I don't get what a Relayer is exactly.


texts: gas required exceeds allowance or always failing transaction in local permissioned Node

texts:
I am facing the some issue with gas but i do not have any modifiers in my contract. Even a simple setter-getter contract shows the following Error

  Error: gas required exceeds allowance or always failing transaction

The above error is displayed when i try to estimateGas for setting a value for the string variable using setter().
If i directly execute the transaction without estimateGas then i get a transaction Hash. when transaction is checked the transaction status is as follows

  0x0 Transaction mined but execution failed

Contract:

pragma solidity ^0.5.0;

contract SampleContract{
    string public str;
    constructor()public{
        str="Hello World!";
    }
    function setter(string memory s)public{
        str=s;
    }
}

  Note: Contract Deployed directly in Geth-Console of locally created Node

  Using Private Permissioned Node Quorum (v 2.4.0)
  Solc to compile and generate abi and bytecode

Can anyone please solve my issue.


texts: Can I use an address value in such a hash function

texts:
I have a method which updates 3 mappings in my contract.
To save data I use some items properties and message sender address, which allows easily to get users data.

mapping(bytes32 => uint256) private uintStorage1;
mapping(bytes32 => uint256[]) private arrStorage2;

function buy(uint256 itemId, address newOwner) public returns(uint256) {
    uintStorage1[_myHashFunc('item1', newOwner)]++;
    arrStorage2[_myHashFunc('type1', newOwner)].push(itemId);
    arrStorage2[_myHashFunc('id1', newOwner)].push(itemId);
}

here is a hash function which I use for that:

function _myHashFunc(string str1, address addr) private pure returns(bytes32) {
    return keccak256(abi.encodePacked(str1, addr));
}

it works fine when I use Ganache, but when I deployed such a contract in the main network it stopped working.

I think that the main problem is my using an address value in that hash function, because my other one which doesn't use address value works fine.

here is that function without address value:

 function _myHashFunc2(string str1, uint256 int1) private pure returns(bytes32) {
    return keccak256(abi.encodePacked(str1, int1));
}


texts:
I have a web3J application that is supposed to deploy a contract (by calling a function on another contract) then listen for the contractCreatedEvent that is fired by the factoryContract and then call a function on the new contract.

ContractA = Factory Contract that deploys ContractB and sends EVENT
ContractB = Some Contract with function fuBar()

So I do the following:

ContractA.deploy()
Address contractB = event.address
ContractB.at(contractB).fuBar()

Now my problem is, that both, the deploy as well as the fuBar transaction are mined in the same block and fuBar even has a higher position thus not executing a call on the new contract but rather on an address with no code (yet)

can someone explain what is happening here? why do i get the address/event before the contract is actually deployed and operable?


texts: The method eth_compileSolidity does not exist/is not available at Object.InvalidResponse stacktrace

texts:
I am new to Ethereum. Trying to run a smart contract. I verified the contract content by running it on online compiler. But I am getting an error at the following line of code.

var simpleCompiled = web3.eth.compile.solidity(contractcontent);

I tried it with web3 version 0.15.3 and 0.20.1 but same error is repeated.


texts: How to get ETH contract balance with Ethers.js

texts:
I am trying to get the ETH balance of a contract:
const balance = await contract.getBalance();

but it fails:
TypeError: contract.getBalance is not a function

What I do wrong and how to fix the error?


texts: Using Chainlink External Adapters doesn't return anything

texts:
Trying to use this Bitcoin Adapter
But having some issues specifically with the copyPath argument and the callback arguments.
For one, I would like to retrieve multiple parts of the JSON that is output, so I would think I need multiple copyPath arguments in my request but can't find any examples of that. I'm also not sure what arguments the callback fulfill function should have, I assume the type is string, but haven't found that defined anywhere.
Here's what I have so far, the node gets my request and processes it, but I'm getting nothing back in my callback (or maybe it's never being called).
    string public addr1;
    string public addr2;
    uint public value1;
    uint public value2;

    function makeRequest(string memory btcTX_ID) public {
        Chainlink.Request memory req = buildChainlinkRequest(jobId, address(this), this.fulfill.selector);
        req.add("rpc_command", "getRawTransaction");
        req.add("tx_id", btcTX_ID);
        req.add("copyPath", "result.data.tx.vout.0.scriptPubKey.addresses");
        req.add("copyPath", "result.data.tx.vout.0.value");
        req.add("copyPath", "result.data.tx.vout.1.scriptPubKey.addresses");
        req.add("copyPath", "result.data.tx.vout.1.value");
        sendChainlinkRequestTo(oracle, req, fee);
    }

    //callback function
    function fulfill(bytes32 _requestId, string memory _addr1, uint _value1, string memory _addr2, uint _value2) public recordChainlinkFulfillment(_requestId) {
        addr1 = _addr1;
        value1 = _value1;
        addr2 = _addr2;
        value2 = _value2;
    }

Here's the doc page for using External Adapters in Solidity


texts: Who pays the expenses of running all contract codes again and again?

texts:
As far as I understand, each new node that downloads the blockchain must run all code in all contracts from the beginning until the present time (is this correct?).

This means that a contract in an early block has to be executed many times, by every new node.

However, the contract caller only paid the cost (in gas) once - the first time he sent the function call.

Isn't there an economic problem here? A person pays only once, but his actions create an unbounded cost for society?


texts:
I just generated new Ethereum account with
geth account new

Your new account is locked with a password. Please give a password. Do not forget this password.
Password:
Repeat password:

Your new key was generated

Public address of the key:   0xE582f436A505EEe5E2D8F2F70752e876F51abC0C
Path of the secret key file: /Users/user/Library/Ethereum/keystore/...--e582f436a505eee5e2d8f2f70752e876f51abc0c

- You can share your public address with anyone. Others need it to interact with you.
- You must NEVER share the secret key with anyone! The key controls access to your funds!
- You must BACKUP your key file! Without the key, it's impossible to access account funds!
- You must REMEMBER your password! Without the password, it's impossible to decrypt the key!

Now what exactly here in this JSON is private key?
I have found https://github.com/ethereumjs/keythereum
that say geth is using

key derivation functions (PBKDF2-SHA256 or scrypt), symmetric ciphers (AES-128-CTR or AES-128-CBC)

That is again more confusing, as private key should be long number
If private key is encrypted how to decrypt and see it?
{
  "address": "e582f436a505eee5e2d8f2f70752e876f51abc0c",
  "crypto": {
    "cipher": "aes-128-ctr",
    "ciphertext": "19f04d75a17df3f6310f934628358ebb137e4b64eb4e320e5df5991d7739e131",
    "cipherparams": {
      "iv": "b6f5905c11bda21b4fcd68dc1b6e0cb4"
    },
    "kdf": "scrypt",
    "kdfparams": {
      "dklen": 32,
      "n": 262144,
      "p": 1,
      "r": 8,
      "salt": "1c9005124e67c5cee8cc469b85274c8fde2bc204dcfc9262b49389172231c4d5"
    },
    "mac": "0ef27b22356a8cb01b5dfab025132b56033a5f2e6c55e21ffca8c5036e19f85f"
  },
  "id": "54741ac3-7f23-46f9-b2fd-d7358af5ec76",
  "version": 3
}

More theory is in How are ethereum addresses generated?


texts:
I am going to mint a collection of 10,000 NFTs. However, I've become very concerned over the gas costs associated with such an endeavor. I was wondering if someone could help me understand the following:

When I created an account on OpenSea there was a one time gas fee. After that I can mint as many NFTs and create as many collections as I want all for free. How is this possible?

If I programmatically mint NFTs on the mainnet for example by following this tutorial, I must pay the gas price when I deploy the contract and for each NFT I mint right? Seems like it will cost a fortune to mint 10,000 if I have to pay a substantial gas price for each mint.

I've looked at Cargo which is supposed to be designed for batch minting but it seems like there is actually a lot of hidden costs.

Is there an inexpensive solution (<US$500) for me to deploy 10,000 NFTs other than uploading them one by one manually onto OpenSea?


texts: How to assign value to function(transfer) 's parameter

texts:
I use these codes(@Lauri Peltonen ) however  I tried 5 ether and 500, but I found it had an error in remix " like I need to add payable to constructor, but I already added". What does that mean?

  pragma solidity ^0.5.1;

    contract MyContr {
        function transfer(address payable receiver, uint amount) public {
            require(address(this).balance >= amount);
            receiver.transfer(amount);
        }
    }


texts: Change in genesis file without creating chain from the start

texts:
We're working with private Blockchain(PoA, 2 consensus node) and we've already created few blocks. Now we'd like to add some change in genesis file. So, basically question is, how can we support previous chain, also new blocks should be generated on basis of updated genesis file.

Could we use hard fork over private chain? if yes then how will it helps in our case?


texts: Accessing modifier of another smart contract - Role Based Access Control

texts:
I am trying to create a simple role based access control system for the contracts I have created.
I have two smart contracts, one named Users that stores all of the users details as well as the type of account created. The other smart contract is the logic main logic and functions a user can access. I have created a function in the Users contract to check if a user is of a specific user type, e.g. manufacturer. I have also created a modifier in the Users contract to require that this function is called to check if the user is a manufacturer and in turn the main function in the SupplyChain contract uses the correct modifier in the users contract to check the user type before accessing the logic of the function.

SupplyChain.sol

pragma solidity ^0.5.16;
import './Users.sol';

contract SupplyChain is Users{

mapping (uint => Item) items;

 struct Item {
    uint    sku;  // Stock Keeping Unit (SKU)
    uint    upc; // Universal Product Code (UPC), generated by the Farmer, goes on the package, can be verified by the Consumer
    address ownerID;
}
function pfunc(uint _upc, address _owner) public onlyManufacturer(msg.sender) view returns(address){
    return _owner;
  }

Users.sol

pragma solidity ^0.5.16;
contract Users {

    enum UserType{
        Producer,
        Manufacturer,
        Supplier,
        Retailer,
        Consumer
    }

    modifier onlyManufacturer(address _owner){
        require (isManufacturer(_owner), "Only Manufacturer's are allowed to access this function");
        _;
    }

function isManufacturer(address _userAddress) public view returns(bool){
        UserType temp = UserType.Manufacturer;
        if(users[_userAddress].userType == temp){
            return true;
        }else{
            return false;
        }
    }

When I call the 'isManufacturer' function straight from app.js to check the current users account type it returns that the user is a manufacturer however, when I try to call 'pfunc' with the same address it returns the following error:

MetaMask - RPC Error: [object Object]
{…}

code: -32603

data: Object { message: "VM Exception while processing transaction: revert Only Manufacturer's are allowed to access this function", code: -32000, data: {…} }

message: "[object Object]"

stack: "i@moz-extension://2dd2e06e-9e5f-4fa5-819d-629e5b9dc759/background.js:1:1186307\na@moz-extension://2dd2e06e-9e5f-4fa5-819d-629e5b9dc759/background.js:1:1188007\ninternal@moz-extension://2dd2e06e-9e5f-4fa5-819d-629e5b9dc759/background.js:1:1188294\nf@moz-extension://2dd2e06e-9e5f-4fa5-819d-629e5b9dc759/background.js:1:1209307\n[512]</</t.exports/<@moz-extension://2dd2e06e-9e5f-4fa5-819d-629e5b9dc759/background.js:1:1208519\n"

This is how I am calling the function through web3:

App.contracts.SupplyChain.deployed().then(function(instance){
      instance.pfunc(1,App.metamaskAccountID).then(function(error, result){
        if(!error){
          console.log(result);
        }else{
          console.log(error);
        }
      })
    });

I don't know why I keep getting this error, pressumably the user address is not being recognised when passed from one smart contract to another, can anyone help me out?


texts: Add new field 'message' for sending text message to specific address

texts:
I have created a private net following https://omarmetwally.blog/2017/07/25/how-to-create-a-private-ethereum-network/ holding 4 peers. I run Ethereum Block Explorer ( https://github.com/etherparty/explorer).

When I run Ethereum node, at the browser I could connect into the Ethereum Block Explorer from localhost:8000.

Transaction Details give :

Transactions - contained in current block
Transaction #1
Hash #  0x080af6ed6ecdf81a9af989a21e3a90f3379a84a1fc80ba7c656e1a8afd6e441c
From    0x5aff57c0d28d49fea39250293e0400d31947d226
To  0x9ecad548e91c02c8344654d13ef6ff075f096651
Gas 90000
Input   0x4d657373616765207375636365737366756c6c7920646973706c61796564
Value   "100000000000000000000"

I need to pass text message along with transaction. So I followed the command :

eth.sendTransaction({from: '0x5aff57c0d28d49fea39250293e0400d31947d226', to:'0x9ecad548e91c02c8344654d13ef6ff075f096651', value: web3.toWei(100, "ether"),data:web3.toHex('Message successfully displayed')})

The 'message' is shown as hexa value in Input field. Can't a text message displayed in block explorer? Can a new field be added to hold text message?


texts: "'parity' is not recognized as an internal or external command, operable program or batch file."

texts:
I downloaded Parity installer from here : https://www.parity.io/ and then installed it on computer with OS Windows 8.1. Then even I restatred computer.

However, when I use following command:

parity db kill --chain ropsten

I receive following error message:

'parity' is not recognized as an internal or external command, operable program or batch file.

Does it mean that Parity is not yet installed ? Or I need to do some complementary steps to finalise installation ?


texts: How to reset all the balances of users in an ERC-20 to 0? How to recyle an ERC-20

texts:
Assume we have Token 1 which is an ERC-20 contract that has issued 200 tokens to User A.
Then we want to have Token 1 'recycled' into a new token, rather than create a new contract.
After the contract has been recycled, User A's 200 tokens should return to 0.
Recycled Token then issues 100 tokens to User A.

User A should only have 100 tokens.

Is this possible?

The first solution I thought of is to iterate over all the addresses and set them to 0, but this is unfeasible, clearly.

The second solution I thought of was to use a "check" function that checks which token epoch the user has tokens from, and then burn the epoch tokens are are not active. The problem is still that balanceOf would return their old, non recycled, balance until this they call into the contract. That could lead to some issues.

The clear solution is to issue a new ERC-20 token contract, but I wanted to explore if this was possible.


texts: Solidity Help - Undeclared Identifier - onlyOwner WithdrawEther

texts:
I'm new to Solidity and attempting to add a withdraw ether function for my contract which enables me to release funds the  parent contract account, but the compiler (remix) keeps on giving me an undeclared identifier error: onlyOwner is an undeclared identifier.

Any help? Do I have to define, and if so, how?

Please and thanks for the help!

Here's my code: (Concensys Template)

pragma solidity ^0.4.18;import "./EIP20Interface.sol";
contract BLUBLOXX is EIP20Interface {

uint256 constant private MAX_UINT256 = 2**256 - 1;
mapping (address => uint256) public balances;
mapping (address => mapping (address => uint256)) public allowed;
/*
NOTE:
The following variables are OPTIONAL vanities. One does not have to include them.
They allow one to customise the token contract & in no way influences the core functionality.
Some wallets/interfaces might not even bother to look at this information.
*/
string public name;                   //fancy name: eg Simon Bucks
uint8 public decimals;                //How many decimals to show.
string public symbol;                 //An identifier: eg SBX

uint price = 0.001 ether;

function BLUBLOXX(
    uint256 _initialAmount,
    string _tokenName,
    uint8 _decimalUnits,
    string _tokenSymbol
) public {
    balances[msg.sender] = _initialAmount;               // Give the creator all initial tokens
    totalSupply = _initialAmount;                        // Update total supply
    name = _tokenName;                                   // Set the name for display purposes
    decimals = _decimalUnits;                            // Amount of decimals for display purposes
    symbol = _tokenSymbol;                               // Set the symbol for display purposes
}

function transfer(address _to, uint256 _value) public returns (bool success) {
    require(balances[msg.sender] >= _value);
    balances[msg.sender] -= _value;
    balances[_to] += _value;
    Transfer(msg.sender, _to, _value);
    return true;
}

function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
    uint256 allowance = allowed[_from][msg.sender];
    require(balances[_from] >= _value && allowance >= _value);
    balances[_to] += _value;
    balances[_from] -= _value;
    if (allowance < MAX_UINT256) {
        allowed[_from][msg.sender] -= _value;
    }
    Transfer(_from, _to, _value);
    return true;
}

function balanceOf(address _owner) public view returns (uint256 balance) {
    return balances[_owner];
}

function approve(address _spender, uint256 _value) public returns (bool success) {
    allowed[msg.sender][_spender] = _value;
    Approval(msg.sender, _spender, _value);
    return true;
}

function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
    return allowed[_owner][_spender];
}

function() public payable{

    uint toMint = msg.value/price;
    totalSupply += toMint;
    balances[msg.sender]+=toMint;

    Transfer(0, msg.sender, toMint);

}

function withdrawEther() external onlyOwner {
owner.transfer(this.balance);


texts: Detection of var vulnerability: problem with search string

texts:
SmartCheck tool at:
SmartChek: Static Analysis of Ethereum Smart Contracts
suggests detection of 'var' key word in the smart contract by searching the assignment statement such that the Left Hand Side of assignment statement contains var keyword and Right Hand Side contains the integer value.
 But it says usage of search string: (matches ˆ[0-9]+$). I can’t understand the use of ‘$’ sign in the above search string.

Some body please guide me.


texts:
I withdrew 681 OMG tokens to myetherwallet yesterday. The withdraw is showing as completed in the exchange however the tokens didn't arrive in my wallet. I have verified that the address is correct. When looking at the transaction details it shows the following error message:

Warning! Error encountered during contract execution [Bad instruction]

Has anyone else experienced this issue and what was the solution? I have reached out to Bitfinex support and am awaiting their response...


texts: Interfacing with Uniswap/Pancakeswap locally

texts:
I'm interacting with PancakeSwap for the first time, as I'm developing a token that interfaces with PancakeSwap. Ideally I'd like to iteratively test it without deploying to a live network.
Must I deploy to the main network/testnet, or am I able to test it locally (e.g. Hardhat network)? If the latter, how?