texts: Reentrancy protection against multiple entries at once

texts:
I'm concerned about the security of the Reentrancy pattern that we can use in Solidity to prevent from calling multiple times a same function at the same time.
This protection is nicely implemented here:
https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/ReentrancyGuard.sol.
But for my question, I did a smaller version merging the code of the modifier inside the function:
contract Contract1 {
    bool locked;

    function f() external {
        require(!locked, "Reentrant call");
        locked = true;
        // Do something
        locked = false;
    }
}

According to my understanding, in Solidity, on the Ethereum Virtual Machine, it is impossible to execute more than 1 instruction at a time, each instruction is executed sequentially, not in parallel. That's why before to execute locked = true, first require(!locked, "Reentrant call") have to be executed (and valid).
But would there be a possibility for 2 concurrent requests (let's say from user A and user B, or even from the same user) on f() to sequentially execute those instructions in this order:

require(!locked, "Reentrant call")
require(!locked, "Reentrant call") (which would also be valid at this stage)
locked = true
locked = true

If so, // Do something would be executed twice.


texts: How are ERC-721 protocol tokens different from Ardor assets? Is there a pro/con data sheet?

texts: ERC-721 protocol is used to create unique tokens like crypto kitties, but I'm curious has anyone compared it to the Ardor Ignis singleton assets as it seems like it does something similar. Is there a pro/cons data sheet?


texts:
I am new and I am trying to make my first transaction using geth and truffle.
to specify a sender address I type in the truffle console:
src = web3.eth.accounts[0]
but I get "undefined"
if I type accounts = web3.eth.getAccounts()  it seems it works and I get an array with 10 accounts
but if I want only the first account of the list and I type src = accounts[0] I get again "undefined"
What am I doing wrong?
Many thanks


texts: Remove array element and pass the new one at this position

texts:
There is a contract where we have artists and anybody can buy an artist, then he becomes the owner of this artist. Also, I have owners array and bulkSend function that sends ETH to all addresses of the owners array.

pragma solidity >=0.4.22 <0.7.0;

contract Cinema {

    struct Artist {
        string name;
        uint price;
        address owner;
    }

    Artist public artist;
    mapping (uint => Artist) public artists;
    address payable private manager;
    address payable[] public owners;
    uint numArtists;

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

    function bulkSend(uint256 amount) public payable {
        uint256 share = amount / owners.length;
        uint256 length = owners.length;
        uint256 currentSum = 0;
        for (uint256 i = 0; i < length; i++) {
            require(share > 0);
            currentSum += share;
            require(currentSum <= msg.value);
            owners[i].transfer(share);
        }
    }

    function addArtist(string memory name, uint price, address payable owner) public returns(uint artistID) {
        artistID = numArtists++; // artistID is return variable
        artists[artistID] = Artist(name, price, owner);
        owners.push(owner);
    }

    function contribute(uint artistID) public payable {
        Artist storage c = artists[artistID];
        require(msg.value == c.price, "Wrong amount");
        manager.transfer(msg.value / 10); // Send 10% to the manager
        bulkSend(msg.value * 9 / 10); // Send 90% to owners
        c.owner = msg.sender; // Set contributor as owner of the Artist
        delete owners[c.index];
        owners.push(msg.sender); // Add contributor to the owners array
    }
}

The question is can I delete an element in the array and somehow past a new element at this position (.push doesn't allow to do this)? It's important to keep the order of the elements.


texts:
When examining OpenZeppelin's library of contracts for ERC721 Tokens, you'll find that all tolled, there are literally five flavors of the transfer method, as follows:

transferFrom(from, to, tokenId) - where this function then internally calls
_transfer(from, to, tokenId)

Then there's:
3. safeTransferFrom(_from, _to, _tokenId) - where this function internally calls the
4. safeTransferFrom(from, to, tokenId, "") - which has that additional bytes array argument, and which then calls
5. _safeTransfer(from, to, tokenId, _data) - which - like #1 also then internally calls
_transfer(from, to, tokenId)
So basically, no matter which of these you're calling, all roads eventually lead to the _transfer(from, to, tokenId) method, which is where the real business of transferring takes place.
I do understand wanting in general to have that additional safe flavor for transfer, but...

why have so many of them? Specifically,
what sort of data might one pass when using safeTransfer(from, to, tokenId, _data)? Like what's a good example for that? (Asking cause I've yet to come across a case where that one was used)
if you choose to go with option # 3 (safeTransferFrom(_from, _to, _tokenId)), you will literally end up calling a total of 4 functions (because of how they're internally "chained" together) in order to accomplish what you want - which I think means paying 4 times as much gas (maybe not exactly 4x, but certainly more than you would for calling just one function) - so why/when would you actually want to do that?

Would love any insights into all this.


texts:
Can you provide names of Big Data or IoT projects (other than Slock.it) currently running on Ethereum?

I'm especially interested in how Big Data could use it or whether a combination of IPFS and Ethereum could disintermediate this industry.


texts: Solidity - multiplying tokens with price

texts:
I'm writing a simple exchange script. It contains my token with 18 decimal places and ether (which is very similar).
Users can add buy / sell offerts and the script displays them.

I can send the addBuyOffert transaction there which has two arguments: tokensAmount and priceForOneUnit (one unit means equivalent for 1 ether). On the ending of the BUY function it multiplies tokens by price and removes sender's wei equivalent. When user cancels the offert, he gets wei back.

When I was testing the script on microvalues without any decimal places it was working great. For example I called buy offert with 10 tokens, 10 wei and it removed from my account 100 wei (10 tokens * 10 wei) and the offert was added without any problems.
The problem appeared after adding decimals and working with greater numbers. The final price was for not 1 token but for 1000000000000000000. For example when I put 0.02 coin and 0.01 eth to add buy offert, it sends 20000000000000000, 10000000000000000 and tries to multiply it which fails with SafeMath. Also tried with div with 1 ether and it also didn't give me precise results.

Knowing this I changed my code a bit. This is what I did so far, but I keep in mind that this isn't the best solution, because the first "if" gives me wrong result - tried with 1.1, 1.1, expected 1.21, but got 1.1 of eth to remove.

uint eth = 1 ether;
if(tokensAmount > eth)
{
    finalPrice = pBuyPrice.mul(tokensAmount.div(eth));
}
else if(tokensAmount < eth)
{
    finalPrice = pBuyPrice.div(eth.div(tokensAmount));
}
else
{
    finalPrice = pBuyPrice;
}

How can I make this calculation working properly?


texts: how to set an ether value as a function parameter?

texts:
I work on Truffle and my project is simple. contract A should transfer some ether to contract B. contract A is funded enough. In contract A, there is a function called payment that performs the transfer and uint val is its parameter that tells the function the ether value to transfer. Whenever i try the function in Truffle console the following error occurs:

Error: invalid number value (arg="val", coderType="uint256", value=1000000000000000000)

I don't know how to assign a correct value as an argument to payment function.

contract A:

pragma solidity ^0.5.12;

contract A{

    event Payment(address receiver, uint value);

    function payment(uint val) public payable returns(string memory){
        address(uint160(0xae1b77270ae418bDd72e14e842F57D9EC2DBD1d8)).transfer(val);\\Transfer to contract B
        emit Payment(0xae1b77270ae418bDd72e14e842F57D9EC2DBD1d8, val);
        return "Payment done successfully";
    }

    function() external payable{}
}

contract B:

contract B{
    function balanceView() public view returns(uint){
        return address(this).balance;
    }

    function() external payable{}
}

The command i tried in Truffle console:

truffle(develop)> A.deployed().then(function(ins){app=ins})
undefined
truffle(develop)> app.payment.sendTransaction(1000000000000000000)


texts: What happened when etherscan sats "Out of Gas"

texts:
I looked in Ethereum scan and saw often a red marked with transactions telling "Out of Gas"
What happens with such transactions?


texts: 調用transferFrom的函數時出現錯誤顯示Reason provided by the contract: "ERC20: transfer amount exceeds allowance

texts:
What's the problem?
pragma solidity ^0.6.0;
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/proxy/Initializable.sol";
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/IERC20.sol";
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/SafeMath.sol";
contract Test {
    using SafeMath for uint256;
    IERC20 public toke;
    function f(IERC20 _token)public{
        toke=_token;
    }

    function y(address u,uint256 i)public{
        toke.approve(msg.sender,i);
        toke.transferFrom(msg.sender,u,i);

    }

}

transact to GLDToken.transferFrom errored: VM error: revert. revert The transaction has been reverted to the initial state. Reason provided by the contract: "ERC20: transfer amount exceeds allowance". Debug the transaction to get more information.


texts: How to write to contract directly? (other than Etherscan)

texts:
I would like to "withdraw" from WETH into ETH: https://etherscan.io/token/0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2#writeContract
But the Etherscan does not work for me right now :(

Tried running repo: https://github.com/etherscan/writecontract
But a little bit fiddly with ABI, contract address...
...maybe there is another place (another explorer) to "write" to the contract directly?


texts: Can you call a base contract's fallback function?

texts:
Can you call the fallback function of the base contract that the current contract is inherited from?

contract LittleA {
  function() {
    doLittleStuff();

    // how do I call the base contract's fallback function?
  }
}

contract A {
  function() {
    doStuff();
  }
}


texts: how to check if bytes32 begins with certain bytes?

texts:
how do i gas-efficiently check if a bytes32 begins with certain bytes?
the user gives me a bytes32 input, and i want to check if it start with 4 zero bytes.
thank you


texts:
I read some sources that say transactions are anonymous, some that say they are semi-anonymous, and some that say they are not anonymous at all. In what ways are the transactions anonymous and in what ways are they not anonymous?

And how does that differ from Bitcoin's pseudonymous transactions?


texts: Programatically determine confirmation of transaction

texts:
Assume I request a transaction A from a Ethereum Node (let's say Infura for simplicity) by using getTransactionByHash shortly after the transaction was processed by the network (currentBlockNumber = A.blockNumber).
After some time x I want to determine if A has reached enough confirmations (Let's say 12).
Is it enough to request the current block number and see if the difference of currentBlockNumber - A.blockNumber is greater than or equal to 12? Can the block become an uncle and thus not be included in the current head of the blockchain? If so, how do I determine if the transaction is confirmed with 12 blocks safely?


texts:
I'm implementing a function and I'm getting an unexplained bug from the compiler

function _incrementMonths(uint16 _months, uint _timestamp) internal returns (uint){
    DateTime dateTime = new DateTime();
    uint16 year = dateTime.getYear(_timestamp);
    uint16 month = dateTime.getMonth(_timestamp);

    uint16 newMonth = month + _months;
    while(newMonth > 12){
        newMonth -= 12;
        year++;
    }

    // get new timestamp
    return dateTime.toTimestamp(
        year,
        newMonth,
        dateTime.getDay(_timestamp),
        dateTime.getHour(_timestamp),
        dateTime.getMinute(_timestamp),
        dateTime.getSecond(_timestamp)
    );
}

This function gives the following error

browser/Payroll.sol:327:16: TypeError: Member "toTimestamp" is not available in contract DateTime outside of storage.
        return dateTime.toTimestamp(
               ^------------------^

The contract I'm referencing is found here: https://github.com/pipermerriam/ethereum-datetime/blob/master/contracts/DateTime.sol . The method I'm calling is found here https://github.com/pipermerriam/ethereum-datetime/blob/master/contracts/DateTime.sol#L165

I've been trying to debug this, but I don't see what is causing this error. What is the cause?


texts:
I am sorry if this question seems to be somewhat bad, but I am trying to work out the stack representation of the following opcodes:

PUSH1 60
PUSH2 40

would the stack representation of this be:

[4040]
[60]

so that 2 bytes of 40 are pushed into one index of the stack, or are 2 bytes of 40 indiviudally pushed into the satack, as in:

[40]
[40]
[60]

again sorry if the question is vague. Many thanks.


texts: I'm trying to deploy smart contract on Private blockchain(quorum). And run the dapp on private blockchain. But I'm unable to connect the metamask with quorum network. The quorum is currently running on VM.  Can anyone help me with this?


texts: swap token for usdt, create function send 1 usdt and receive 1 token

texts:
I need to create a smart contract where each token of mine will be exchanged for 1 usdt, that is, a person sends 1 usdt to the function and he adds 1 token to his balance sheet.
How can I do it? with eth it is simple but usdt is being a challenge for me.
Does anyone have an example?
How can I test on the ropsten network?


texts: how many transactions could be included in a new block from the same account?

texts: How many transactions could be included in the next new block from the same account? From my understanding, every transaction would have a unique nonce. This nonce of an account would be increased by 1 for every transaction? So I wonder if it can just have at most 1 transaction from the same account.


texts:
library Lib{
    struct Data {
        mapping (uint => uint) a;
    }

    function inc(Data self) internal{
        self.a[0] =+1;
    }
}
contract Example{

    address recipient = 0x0000cafebabe;

    Lib.Data data;

    function send(){
        Lib.inc(data);
    }
}

Leads to error

7:9: Error: Member "a" is not available in struct Data memory outside of storage.
        self.a[0] =+1;
        ^----^


texts: How to signTransaction of a smart contract methods?

texts:
I have a smart contract contains this method:

function addOneUser (User memory _user) public {

         bytes32 hash = keccak256(abi.encode(_user.name));
         users[hash] = _user;

    }

I want to invoke this method using singTransaction then sendSignedTransaction,
how to encode data (which _user) into transaction raw ?


texts: Is it possible to do transactions in Ethereum without gas fee?

texts:
I have developed a DApp to store various asset details. Obviously, for storing each asset detail we have to pay some amount of transaction fee for it. One of my teachers said to me that Since cryptocurrencies are not widely accepted in some countries(In my country too) and also many people don't have enough knowledge on that, then it will be difficult for them to buy ether and use our application to store the details.
So he suggested me to make an upper layer that looks like a conventional storing method, anyone can come and store the details even if they don't have ether but in the end, the transaction should be stored in the Ethereum blockchain. Because of this, even those who have 0% knowledge on ethereum and those who can't afford ether will indirectly use it. So it is possible to make such an app that do transactions in the underlying layer, if enough normal currencies are received or if the method meets a set of pre-defined rules in the upper layer (Just like how gas-fees are not used in permissioned-blockchain and still the transaction happen after attaining the required properties).


texts: Can you get the Genesis Block info from .stt files?

texts: I have a private chain I changed the genesis block to for a separate iteration using the same parameters but I have something on the initial chain I need and no idea how to get back to the initial genesis, is there anything I can get from the .stt files in the db folder of the chain?


texts: Checking if Contract Withdrawal Is Allowed

texts:
I am trying to conceptualization how a specific kind of smart contract would be written.

The contract would basically handle deposits and withdrawals of ETH or some sort of ERC20 token.

The balances would then be used to play various off chain games, mostly multiple player casino style stuff like Texas Holdem. The games are offchain because they require alot of operations and the Tx fees would not be user friendly.

Users would increase (or decrease) their balances inside the contract from playing these games.

I want to give the users the ability to withdraw their balances back to their wallets at anytime but I have to be able to check against the game servers to make sure they are not currently in a game while they are trying to withdraw.

I am trying to prevent a scenario where a player would enter a game (like poker) stake their balance off chain but withdraw it from the contract while the game is in progress. Then if they lose there is no balance to transfer to the other player.

I'm not sure what the correct approach would be to do this?
Could creating a token/custom wallet or oraclizing the withdrawal help in anyway?

Any insight would be greatly appreciated!

Thank You


texts: How to send a fixed amount of ether to a smart contract from an account?

texts:
Is it possible to send a fixed amount of ether to  smart contract from an account every time a function is executed or button is clicked?
No input fields should be used.


texts: How to solve this error: "Cannot read property 'address' of undefined"?

texts:
ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'address' of undefined TypeError: Cannot read property 'address' of undefined

This is my code that uses web3.js:
public getContract() {
    return new Promise((resolve) => {
      const web3 = window.web3;
      let networkId: string | number;
      web3.eth.net.getId()
        .then((netId: any) => {
          networkId = netId;
          const abi = kltArtifacts.abi;
          //console.log("my endpoint ---------------");
          console.log(kltArtifacts.networks[networkId]);
          const networksAddress = kltArtifacts.networks[networkId].address;
          const KltStore = new web3.eth.Contract(abi, networksAddress);
          resolve(KltStore);
        });
    });
  }


texts:
Sorry, I'm a newbie on ERC721 token. Please help.

I have deployed ERC721 contract in the localhost testnet. I use looping function for mint token and it works.

But when I use looping function for send token, it's failed with revert response. This is my code and response

What's the problem? Can anyone help me? thanks


texts: Must I run node and compile/migrate contracts on AWS Instance for WebDapp?

texts:
I am launching a semi-decentralized webapp using AWS and was wondering if I must continually run a node on AWS for it to work. Currently, if I don't run a Rinkeby node and compile/migrate the contract in my AWS instance then it won't work, but I may just be doing something wrong.

Thank you.


texts:
If someone mistakenly send some amount of USDT to an Ethereum Address:

Will this amount of usdt (ERC20 Tether) be deducted from sender wallet?
If it was sent how can she revert it?


texts: Type error, unit256 is not implicitly convertible to expected type struct

texts:
Using sol compiler 0.5.1
I am trying to fetch data from old smart contract's function called people, the smart contract is already deployed on the blockchain
mapping(address => Person ) public people;

and in new contract i imported it and define like this
ADNIOX token;

constructor () public {
                        token = ADNIOX(0x5244e79314c710E5cA2715c071F3d2750CcAEa90);
                            }

Below is the response I get.
token.people(_addr);

now i want do check some variable values from above response and process according to it.
Person memory p = token.people(_addr);

(uint a,address b,uint256 c,uint256 d,ADNIOX.userState e ,ADNIOX.withdrawState f ,ADNIOX.remainToken g ,uint256 h,uint256 i) = token.people(_addr);

I tried both ways but it haven't worked for me.
The contract is deployed here: https://ropsten.etherscan.io/address/0x6dc4e20f7fd3540793d9dcb337667f5c5b8f0cb2#readContract
The contract gives the values of whole object

The problem for me is that I want to check the value of one of these variables and compare it to my defined criteria and then proceed to complete the code.


texts:
When trying to transfer funds out of my ether.li account, I'm always getting an error message that I'm entering the wrong code. But it's definitely correct. Ether.li support doesn't reply.

Does anyone know of ANY solution that helps me transferring ether out of my wallet? Bit frustrated by know.. more than happy to compensate for efforts if successful.


texts: Are gasless functions that can be performed client-side possible in solidity?

texts:
Suppose I have a contract which performs an arbitrary mathematical calculation like:
contract Add2Plus2
{
    ...

    function add2plus2() external view
    {
        return 2 + 2;
    }

    ...

}

The function does not rely on any state information of the contract, and does not actually require any knowledge of what is happening on the Ethereum chain, the EVM or otherwise. It just performs a basic mathematical calculation.
I am aware that view functions do not modify stateful variables within a contract. However, they cost gas to perform.
Question:
Is there a way to define such a function that is performed client-side, without any interaction with the EVM - and hence be gasless? If so, how would such a function be defined?


texts: what is the maximum size of an ethereum transaction?

texts:
I want ot know what is the maximum size of an ethereum transaction ?

I have a DAPP that makes a 1Milion transactions per year, I want to describe the deployment requirements such as Storage, RAM etc ..


texts: Will block numbers be sequential on a sharded blockchain

texts:
When Ethereum shards (assuming it does) will the block numbers across the multiple shards be unique? I doubt it (I don't think the shards can have sequential block numbers and be independent of the other).

Assuming the block numbers across shards are not sequential, then can one distinguish them across chains?

I suppose the shard id plus the block number can be a unique identifier, so perhaps I already answered my own question, but does anyone know?


texts: How can an old deployed contract can call a newly deployed contract?

texts:
As we know, in order for a contract to call the other contract, it needs to know the called contract interface/abstract.

Question 1: Can we pass that interface/abstract as a function argument to a contract?

Question 2: Can we design contract C1 such that it would be able to call a function of another contract C2, where C2  will be deployed after C1 is deployed?


texts: How can I get circulating supply for crypto currency?

texts:
I am looking for an API, where I can get the circulating supply for all crypto currencies?

For now, I found this: https://altcoinmarketcap.com/api.
The problem is that if the site go down , I can not get my circulating supply data.

Is there are more sites that can provide me API fot this data?

Thanks

If I don't want to be dependant on that site, Where can I get the data?

Thanks.


texts:
pragma solidity ^0.4.18;

contract graduate{
     uint studentId;
     string name;
     string major;
     uint totalGrade;

     function setGraduate(uint x, string y, string z, uint v) public{
           studentId = x;
           name = y;
           major = z;
           totalGrade = v;
     }

    function getGraduate() public view returns (uint _studentId,string _name,string _major,uint _totalGrade){
          return studentId;
          return name;
          return major;
          return totalGrade;
    }

}

  browser/graduate.sol:17:9: TypeError: Different number of arguments in return statement than in returns declaration.

  return studentId;

  ^--------------^

same on 4 arguments.


texts:
According to the answer to my previous question here, all state reading in a smart contract is done on the current block - Is state read from the current or previous block for external function calls?

My question now is this: Say I have smart contract C with a uint variable called C that changes a lot of the logic in that smart contract depending upon its value (for a game or something similar).

Player A accesses this smart contract, reads its value as "4" from the current block, and increments C by 1. They then do a lot of interaction with the smart contract based upon the value of C now being "5" and broadcast this to the network.

Player B accesses this same smart contract, also reads the value as "4" from the current block but increments C by 5 instead of 1. They also do extensive interaction with the smart contract assuming the value of C to be 9 after its increment, and also broadcast this to the network.

From the perspective of Player A and Player B, they have both performed legal operations with the Contract assuming C to be of the value "4" at the current block, however in each scenario, the Contract would have updated its internal variables in vastly and potentially contradictory ways.

So what happens when player A and B both broadcast their interaction?


texts: Is the following scenario doable by a smart contract?

texts: I have 2 persons ( say A or B). They want to have the following agreement. Person ‘A’ specify a deposit (x coins ) for user ‘B’ under a certain condition with a future time lock ‘t’. If user ‘B’ provide a valid solution, he will get the deposit. How can we add a fine payment on user ‘B’ to user ‘A’ if he does not provide a valid solution after the time lock ‘t’ ?? Any detailed smart contract solution will be very helpful??


texts: Difference between SMTChecker and Manticore?

texts: Why would I use Trail of Bits' Manticore over SMTChecker, which is baked in the Solidity compiler?


texts: web3 - function returning new contract's address

texts:
I have a factory contract which has a function which returns a new contract:

contract AddOrRemoveAdminVotingBuilder
{
    function build(
        address pPlatform,
        address pAdminManager
    )
        external
        returns(address)
    {
        return address(
            new AddOrRemoveAdminVoting(
                pPlatform,
                pAdminManager
            )
        );
    }
}

I'm trying to receive the address from my website script with web3.
The usual async function call returns txhash.

Tried this:

votingBuilders[0].build(platform.address, adminManagerAddress, function(error, result)
{
    let txhash = result;
    console.log("tx: " + txhash);

    let interval = setInterval(function()
    {
        web3.eth.getTransactionReceipt(txhash, function(error, result)
        {
            if(!error && result !== null)
            {
                if(result["status"] == "0x0") // fail
                {

                }
                else if(result["status"] == "0x1") // success
                {
                    incomingVotes.push(result);
                    console.log(result);
                    clearInterval(interval);
                }
            }
        });
    }, 1000);
});

This code puts the successfuly mined transaction to an array. But how can I get the return address of newly created cotract from the return value?


texts: How do I let a user transfer ERC1155 token from my contract address to his address?

texts:
What I want to achieve:
A user should be able to transfer ERC1155 tokens from my contract address to his account.
I've tried two approaches:

Deploy ERC1155 contract, then pass its address to the constructor of the second contract which handles transfers.

This works. Users are able to call buyItems() without any errors.
pragma solidity ^0.8.0;

import '@openzeppelin/contracts/token/ERC1155/IERC1155.sol';
import '@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol';
import '@openzeppelin/contracts/token/ERC1155/presets/ERC1155PresetMinterPauser.sol';

contract ERC1155Preset is ERC1155PresetMinterPauser {
    constructor() ERC1155PresetMinterPauser("https://token-cdn-domain/{id}.json") {}
}

contract testContract is ERC1155Holder {
    IERC1155 private _IERC1155;

    constructor(IERC1155 ERC1155Address) {
        _IERC1155 = ERC1155Address;
    }

    function buyItems(uint256 _itemId, uint256 _amount) external {
        require(_IERC1155.balanceOf(address(this), _itemId) >= _amount);
        _IERC1155.safeTransferFrom(address(this), msg.sender, _itemId, _amount, "");
    }
}

Deploy only one contract for ERC1155 and transfers.

This doesn't work. When a user calls buyItems(), I get this error: execution reverted: ERC1155: caller is not owner nor approved
pragma solidity ^0.8.0;

import '@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol';
import '@openzeppelin/contracts/token/ERC1155/presets/ERC1155PresetMinterPauser.sol';

contract testContract2 is ERC1155PresetMinterPauser, ERC1155Holder {

    constructor() ERC1155PresetMinterPauser("https://token-cdn-domain/{id}.json") {}

    function supportsInterface(bytes4 interfaceId) public view virtual override(ERC1155PresetMinterPauser, ERC1155Receiver) returns (bool) {
        return interfaceId == type(IERC1155).interfaceId
            || interfaceId == type(IERC1155Receiver).interfaceId
            || super.supportsInterface(interfaceId);
    }

    function buyItems(uint256 _itemId, uint256 _amount) external {
        require(balanceOf(address(this), _itemId) >= _amount);
        safeTransferFrom(address(this), msg.sender, _itemId, _amount, "");
    }
}

My question: Why does the first approach work, and why not the second one?


texts:
The answer here is not very useful so I'm asking again. It doesn't matter if you describe the mechanism with the current or future version of MKR.

If the price of DAI on the open market deviates from $1, the supply of DAI has to be altered to bring the price back. How exactly is this done in a decentralized and autonomous way?

The obvious way to me is to lower or raise the interest rates on CDPs thereby making it more or less attractive to open and close them. This would give a perfect feedback mechanism that keeps DAI pegged at an arbitrary price of $1. But I don't think this is actually how the system works in reality.

So here's my question: Assume DAI goes up to $1.10. I do not assume a priori that the price will fall back to $1 anytime soon (if you assume this, then it becomes a self fulfilling prophecy). What is the mechanism that increases the supply of DAI?


texts: Is there a way to deal with desistance in a off-chain game?

texts:
Suppose I want to use blockchain to play chess for money. So, I can register, on the blockchain, a smart contract (a chess game) associated to some amount of ether. If someone wants to join, he or she has to bet the same amount of ether. Whoever wins the game, gets all the ether.

We can implement this smart contract to run on-chain. So, for every piece moved, the player would have to register his decision on the blockchain. This approach would be expensive, because the players would have to pay the transaction fee for every decision they make. And it would be slow, because the game speed would be limited to the speed of the blockchain itself.

To avoid those problems, we could implement this smart contract to run off-chain. Besides the game itself, and the ether, the contract would contain an address to establish a communication (forget about security issues).

The first to play would sign, with his private key, his decision (which chess piece, and its new position) and send it to the other player (not to the blockchain). The second player would sign, with his private key, a "block" that would contain his own decision AND the other decision AND the other signature, and send it to the first player, and so on...

This process would continue until the end of the game. Then, any player could register the final block (containing all the decisions signed) on the blockchain. The contract itself could verify the autenticity and the validity of the decisions (in this case, the moves) and transfer all the ether to the winner.

The problem is: how to deal with desistance?

If a disonest player make a bad move, he can not regret (after send it to the other player), because his decision is signed, but he can just "do nothing" forever. So, he will just ignore the next decision he will receive from the other, and all the ether would be forever blocked for both players. To avoid that, we can implement a timeout.

If the contract has a timeout, another problem emerge: one player (let's call it A) can try to "deceive" the blockchain, pretending that the other player gave up, by refusing to accept the other's decisions.
We can solve that by allowing the other player (let's call it B) himself to register his decision directly on the blockchain, even if it is not his turn to play. This way, the contract will able to know that player B is active.

I believe that, this way, both players would have incentives to play honestly.

If player A doesn't want to (or can't) play anymore, B can send the incomplete game to the blockchain and, after a timeout, if A doesn't publish any valid decision, the contract will asumme that A gave up and will transfer all the ether to B.

If player A believe he has no chance of winning, he will have to send a decision anyway, otherwise player B will register on the blockchain the incomplete game, and the time will begin to count, unless A publish a valid decision.

As you can see, I've just proposed a solution. I did that because I don't even know how to properly describe the problem.

So, now that (I hope) the problem is clear, does this solution work? If not, is there another one? Which?

I used chess as example, but it could be Go, Checker, Hash, Poker, or any other decision game.


texts: Is the address used to deploy contracts in JS tests in truffle always accounts[0]

texts:
I've noticed that the deploying address in my truffle .js tests is equal to the address at accounts[0].

Since it's important to me to test the ownership of a contract, I'd like to know if it's guaranteed that contacts deployed by accounts[0] in the test suite.


texts: Does the new receipt status field report all errors all the way down the call chain?

texts:
See this transaction on etherscan:

https://etherscan.io/tx/0xd20a95a9f051d6961ca766a9b2d0f18b6afdf6d8465931a3f70f2c4b1c023688

Notice the odd note saying some part of that transaction failed but the transaction itself succeeded.

First: why did this happen?

Second: Does the new post-Byzantium transaction receipt status field still exhibit this behavior.

In other words, can a transaction's receipt have a '1' in its status field but still have had one of its internal calls fail?


texts: Is it possible to include Go code in a Solidity contract?

texts: I've learned Solidity first and now I am learning the Go language. Throughout my learning process I am noticing that both languages are very similar. So, is it possible in future to include Go code in a Solidity contract? Or am I wrong?


texts: Validating RSA, Ed25519 and ECDSA signatures in solidity

texts: I am writing a contract in solidity for verifying multiple signature schemes.I found that solidity supports ECDSA, but how do I add check for RSA and Ed25519. is there any existing method/library developed that can be used?


texts: Contract creation with "new" fails, creates EOA not contract account

texts:
Mist 0.8.6, solidity 0.4.2+commit.af6afb04.mod.Emscripten.clang:

I am trying to create a contract within a contract, but the contract created with "new" is not created as contract but as EOA (Address).

Is this a problem of that compiler version or am I doing something wrong?

Simple code example:

pragma solidity ^0.4.2;

  contract ContractB {
    string private name;

    function set_name(string _name) {
      name = _name;
    }

    function get_name() returns(string) {
      return name;
    }
  }

  contract ContractC {
    string private name;

    function set_name(string _name) {
        name = _name;
    }

    function get_name() returns(string) {
        return name;
    }
  }

  contract ContractA {
    ContractB public contractBvar;
    ContractC public contractCvar;

    // Constructor
    function ContractA() {
        contractBvar = new ContractB();
        contractBvar.set_name("contractB");
    }

    function createContractC() {
        contractCvar = new ContractC();
        contractCvar.set_name("contractC");
    }
  }


texts:
i want to copy and paste this code and use it for my token just want to change symbol and everything .
https://bscscan.com/address/0xf38acb6cea8f6701b06ec759f6cbc3fe23f377d3#code
i try to post code but limit issue , well when i try to compile it , its work fine but when i try to deploy it , its show me many contracts image below link..
https://imgur.com/j3Kf0Qa
and some of them works but they are like this
https://imgur.com/g3x0rZM
help me how to deploy this token as mine.


texts: How do I connect to MY full node using RPC

texts: I have a full node(Parity) running at home. I know I can trust this node. How would I go about connecting to it from another computer?


texts: Smart Contract Withdrawal Function Not Working Properly

texts:
For some reason my function keeps throwing at 2nd line, where I'm declaring an uint256 named depositedContribution, I have no idea why and I've tried to debug it for hours with no results, what could be the problem with that particular line?

function withdraw() external stateRequired(State.OPEN) {
            require(contributorData[address(msg.sender)].contribution > 0);

            uint256 depositedContribution = contributorData[address(msg.sender)].contribution.add(contributorData[address(msg.sender)].contributionFee);

            fees = fees.sub(contributorData[address(msg.sender)].contributionFee);
            size = size.sub(depositedContribution);

            contributions--;

            msg.sender.transfer(depositedContribution);

            contributorData[address(msg.sender)].contributionFee = 0;
            contributorData[address(msg.sender)].contribution = 0;
            contributorData[address(msg.sender)].contributed = false;

            emit ContributionWithdrawn(msg.sender, this, depositedContribution);
        }


texts: What happens when transaction is sent from smart contract?

texts: If during smart contract execution it decides to send a transaction, then transaction would be created, validated and broadcasted to the network from all the nodes executing this smart contract. Network would be flooded with same transaction coming from different nodes. How such case is resolved?


texts: How to ensure the state of a smart contract is final?

texts:
If I understand correctly, the state of a smart contract (its data storage and associated events) can only be changed via transactions.

The transactions are stored in blocks and as such in a public chain, due to the nature of the PoW consensus algorithm, may get reversed.

A common practice with currency transactions is to wait for a few "confirmations" in order to ensure the transaction has been "finalized".

Do I have to do the same with smart contract calls? Can I trust a state change in a smart contract immediately or should I wait for a few "confirmations"? Or is it handled already by the implementation?


texts:
I’ve deployed a contract to Ropsten and am testing it manually with Remix. This transaction reverts for whatever reason (we have unit tests where everything looks fine).

In our contract for all of our require statements we have corresponding, custom revert messages. Is there a way to see the revert message in Etherscan or elsewhere to find out why exactly this transaction is reverting?

Appreciate your help.


texts: Why my RX 480 Samsung have slightly lower Mh/s when mixed with a bunch of hynix?

texts:
This is a very minor problem

This is the result of my mining speed

ETH - Total Speed: 176.250 Mh/s, Total Shares: 164, Rejected: 0, Time: 01:03
ETH: GPU0 29.310 Mh/s, GPU1 30.241 Mh/s, GPU2 29.269 Mh/s, GPU3 29.297 Mh/s, GPU4 28.826 Mh/s, GPU5 29.261 Mh/s
GPU0 t=57C fan=71%
ETH: 04/24/17-09:03:41 - New job from europe.ethash-hub.miningpoolhub.com:17020
ETH - Total Speed: 176.020 Mh/s, Total Shares: 164, Rejected: 0, Time: 01:03
ETH: GPU0 29.307 Mh/s, GPU1 30.220 Mh/s, GPU2 29.174 Mh/s, GPU3 29.275 Mh/s, GPU4 28.750 Mh/s, GPU5 29.294 Mh/s
Setting DAG epoch #19...

GPU 1 is samsung and doing 30.220 mh/s as expected.

GPU4 is also samsung with the same set up. 1190 clockspeed and 2135 memory speed. It's doing only 28.750 mh/s

The rest are hynix doing normal 29.25 mh/s

I wonder why.

If I remove the 4 hynix card then both samsung will clock 30.220 mh/s

GPU-z       Watttool    Wattool PCI-e   Claymore    power   voltage mem voltage
1           0           0       0       1   75  910 900 samsung
0           4           20      1       4       910 900 samsung
2           2           8       2       5       910 900
3           3           14      3       2       910 900
4           1           2       4       3       910 900
5           5           36      5       0       910 900

I know that claymore #4 correspond to wattool number 4 too in my graph (index 20). I know that by pressing 4 in claymore and see that GPU go up and down on the correct index at watttool.

You can see that this is the exact same set up with Claymore #1 (watttool 0)

And somehow GPU1 makes 30.220 mh/s and GPU 4 a mere 28.750 mh/s.


texts: Deployed Smart contract methods are not updating the value when restart the geth instance.Why?

texts:
Started Geth using following command

geth --identity "testpvtnode" --rpc --rpcport "8545" --rpccorsdomain "*" --datadir <pvtnetdatapath> --port "30303" --rpcapi db,eth,net,web3,personal --networkid 123 console 2>> Logfile

Accessing the deployed contract through an UI created by referring the following links - (counter, Stack Exchange Question related to UI creation)

I have successfully created the UI and interacted with SmartContract, but the functions are not working properly(able to call the function and transaction done successfully,but counter value is not updating) after I restarted the Geth instance.

Please note : The private net is on my pc( did not set as a server)


texts: how to store some private data on ethereum blockchain?

texts: The idea is to create decentralized system that stores network data  privately  with  random algorithm on  the blockchain  .  This means only smart contract have access to view data and encrypt it  auto  .  other smart contracts and users  cant see the data    even  creator of smart contract can not use  data  because they don't know  decrypt algo


texts:
I am not familiar with Ethereum contract development. I wonder if Ethereum tokens ( like ERC20, ERC1155 or ERC721) have symbol name or not.
On EOSIO the asset is a structure composed of amount and symbol.


texts: Trouble using Parity execute whitehat etc refund contract

texts:
I am trying to use the whitehat refund contract on the ETC chain.  The contract address is here:  0x9f5304da62a5408416ea58a17a92611019bd5ce3

and have mostly been following this tutorial.

The problem is that when I add the contract with abi to parity I don't actually see the withdraw option as one of the queries.

I can go to execute, but then I don't understand what options to choose


texts: Mix does not show the current contract state

texts:
I encouter little problems using mix.
I have the following contract-code:

contract C {
    function C() {}

    struct S {
        address creator;
    }

    mapping(string => S) M;
    uint x;

    function set(string _hash) {
        S memory N = S({
            creator : msg.sender
        });

        M[_hash] = N; //I dont see the mapping in Mix
        x = _hash; //I see 'x' in the current state with the correct value
    }

    function get(string _hash) returns (address addr) {
        return M[_hash].creator;
    }
}

The problem is that I do not see the current state of the contract in the bottom right corner of the IDE. While I see x and the value of _hash, I do not see the state of the mapping(string => S), which should be in the variable M

I thought the mapping maybe is just empty after calling, but when I call the get-function, It returns the correct address from the sender before.

Does anyone had the same issue before or can help me with this?


texts: How to automatically create child contracts?

texts:
Is there any way to create multiple child contracts (with a specific logic inside them) from a parent contract automatically?

My use cases are supply chain management and identity management on blockchain. Given the scale of these cases, I am not inclined to use structs or mappings in one single contract and want to create individual contracts which can be treated individually.

From technical standpoint how can we implement this logic of creating a 'Mother' contract which gives birth to 'Child' contracts based on some business conditions and then these 'Child' contracts function on their own?


texts: How to accept Ether only in certain multiples?

texts: If I wanted a smart contract to only accept Ether payments in multiples of for example 0.05 Ether (so it will accept only exactly 0.05 Ether, 0.1 Ether, 0.15 Ether etc, and send the value back to the sender for anything else) what is the cleanest way of doing this?


texts:
After reading wiki, I understand Ethereum is a programming platform to develop different blockchains.

However, there seems to be one Ether currency that is traded on exchanges.

How to identify that particular blockchain where Ether is used? Is it list of IP addresses of full nodes or other way?

P.S. I wonder if ether and Ether have different meaning?


texts: Synchronisation using geth; DAO fork-check, dropping is the only message recieved

texts:
I'm attempting to synchronise with the blockchain using geth on Win7 64bit.

Presently pretty much all I'm getting is repeats of the same message; timed
    out DAO fork-check, dropping (see bottom).

Every now and then I get something like:

I0906 15:30:04.029772 eth/downloader/downloader.go:1087] Peer de471bccee3d0422 [
hs 0.00/s, bs 0.00/s, rs 0.00/s, ss 0.00/s, miss    0, rtt 13.560187447s]: head
header set (item 0) broke chain ordering: requested 1395022, got 2209108

Earlier on geth shut down on its own, I've since restarted. It looks like there is confusion over the block geth is requesting and the one served by the network...

Is there something obvious I'm not doing?

Is this expected?

What debugging steps should I take?

I0906 15:17:15.469813 eth/handler.go:295] Peer d64f779684a3986e [eth/63]: timed
out DAO fork-check, dropping
I0906 15:17:27.079477 eth/handler.go:295] Peer a979fb575495b8d6 [eth/63]: timed
out DAO fork-check, dropping
I0906 15:17:37.041047 eth/handler.go:295] Peer 1637a970d987ddb8 [eth/63]: timed
out DAO fork-check, dropping
I0906 15:17:48.289690 eth/handler.go:295] Peer 450f0ea6d5b5bb05 [eth/63]: timed
out DAO fork-check, dropping
I0906 15:17:55.155083 eth/handler.go:295] Peer 3806e6f2b68b6e8b [eth/63]: timed
out DAO fork-check, dropping
I0906 15:18:27.007905 eth/handler.go:295] Peer 30dc547dbd116454 [eth/63]: timed
out DAO fork-check, dropping
I0906 15:18:29.160028 eth/handler.go:295] Peer 49eb90bacc21836d [eth/63]: timed
out DAO fork-check, dropping
I0906 15:18:56.982619 eth/handler.go:295] Peer 1637a970d987ddb8 [eth/63]: timed
out DAO fork-check, dropping
I0906 15:19:12.209490 eth/handler.go:295] Peer bb50c8d7c77adf15 [eth/63]: timed
out DAO fork-check, dropping
I0906 15:19:28.016394 eth/handler.go:295] Peer 30dc547dbd116454 [eth/63]: timed
out DAO fork-check, dropping
I0906 15:19:51.930762 eth/handler.go:295] Peer bf83662ffd07c1cd [eth/63]: timed
out DAO fork-check, dropping
I0906 15:19:52.585800 eth/handler.go:295] Peer 53368afb96ab78d4 [eth/63]: timed
out DAO fork-check, dropping
I0906 15:19:59.847215 eth/handler.go:295] Peer 30dc547dbd116454 [eth/63]: timed
out DAO fork-check, dropping
I0906 15:20:24.219609 eth/handler.go:295] Peer 1118980bf48b0a36 [eth/63]: timed
out DAO fork-check, dropping
I0906 15:20:54.413336 eth/handler.go:295] Peer 7cb3f7c58572e50c [eth/63]: timed
out DAO fork-check, dropping
I0906 15:21:28.244271 eth/handler.go:295] Peer 2c2fabac9ef11438 [eth/63]: timed
out DAO fork-check, dropping
I0906 15:22:11.317735 eth/handler.go:295] Peer 390cc42f79d44232 [eth/63]: timed
out DAO fork-check, dropping
I0906 15:22:13.949885 eth/handler.go:295] Peer d64f779684a3986e [eth/63]: timed
out DAO fork-check, dropping
I0906 15:22:24.773504 eth/handler.go:295] Peer 30dc547dbd116454 [eth/63]: timed
out DAO fork-check, dropping
I0906 15:22:28.993746 eth/handler.go:295] Peer 60aa98bd34813843 [eth/63]: timed
out DAO fork-check, dropping
I0906 15:22:39.275334 eth/handler.go:295] Peer 69bfa214a36e0e4d [eth/63]: timed
out DAO fork-check, dropping
I0906 15:23:02.228647 eth/handler.go:295] Peer f6aa7c1d67d3b088

etc...

UPDATE:

Presently trying again as recommended here.


texts: Decoding ethereum leveldb keys and values

texts:
I've created a simple script to read ethereum data from the leveldb using C++. Basically this testing program would print all keys in leveldb to the console.

#include <cassert>
#include <iostream>
#include "leveldb/db.h"
using namespace std;
// g++ leveldb_test.cpp -o test -lleveldb
int main(int argc, const char *argv[]) {
    leveldb::DB* db;
    leveldb::Options options;
    options.create_if_missing = true;
    leveldb::Status status = leveldb::DB::Open(options, "/home/user/.ethereum/rinkeby/geth/chaindata", &db);

    if (!status.ok()){
        cerr << status.ToString() << endl;
        delete db;
        return 0;
    }
    leveldb::Iterator* it = db->NewIterator(leveldb::ReadOptions());
    for (it->SeekToFirst(); it->Valid(); it->Next()) {
        cout << it->key().ToString() << endl;
    }
    delete it;
    delete db;
    return 1;
}

but the results are encoded like this.

How can I output a readable output? Is there a way to decode the ethereum leveldb data? (may be a c++ library?)


texts: Send raw transactions using eth-lightwallet

texts:
I am creating a wallet app and trying to sign and send raw transactions using eth-lightwallet.

function functionCallWallet(){
        var fromAddr = document.getElementById('functionCaller').value
        var contractAddr = document.getElementById('contractAddr').value
        console.log("Contract Address:"+contractAddr);
        var abi = JSON.parse(document.getElementById('contractAbi').value)
        console.log(abi);
        console.log(typeof abi);
        var contract = web3.eth.contract(abi).at(contractAddr);
        var functionName = document.getElementById('functionName').value;
        var args = document.getElementById('functionArgs').value.split(",");
        var gasPrice = 50000000000
        var gas = 3141592
        txOptions = {
            gasPrice: gasPrice,
            gasLimit: gas,
            value: 10000000,
            nonce:2.0e20
            }
        txOptions.to = contractAddr;
        var functionCallTx = txutils.functionTx(abi,functionName,args,txOptions);
        var password = prompt('Enter password ', 'Password');
        lightwallet.keystore.deriveKeyFromPassword(password, function(err, pwDerivedKey) {
        var signedFunctionTx = signing.signTx(global_keystore,pwDerivedKey,functionCallTx,fromAddr);
        console.log("Signed function transaction:"+signedFunctionTx);
        console.log('');
        web3.eth.sendRawTransaction('0x'+signedFunctionTx, function(err, hash) {
            console.log(err);
            console.log(hash);
            });
        })
      }

I am able to sign the transaction correctly. But when it comes to sending the raw transaction on the network I am unsuccessful. In the web3 api they use https://github.com/ethereum/wiki/wiki/JavaScript-API#example-45
they use the ethereumjs-accounts library to serialize the raw transaction to hex. Does eth-lightwallet also have a serialize to hex function so that it could be used and then data is in format used by the web3 sendRawTransaction function or do have to use the ethereumjs-accounts library mentioned in web3 docs ?

I am getting this error, obviously I am not serializing it the correct way but I will put the error anyway

Error: rlp: input string too long for uint64, decoding into (types.Transaction)(types.txdata).AccountNonce
    at Object.module.exports.InvalidResponse


texts: Deploying App on Ropsten or any Test Network

texts:
I have a web3.js application which uses truffle and interacts with smart contracts deployed on Ganache.
How do I deploy my smart contract on a Test Network and interact with it through my application?


texts: Can someone provide a detailed picture of an Ethereum Patricia Tree?

texts:
I am looking for a diagram of a Patricia tree which shows the details of multiple blocks, with multiple transactions in each block. I want to see an actual example of how the chain of blocks will be represented, so I can understand how all of the components will be created i.e. header, extension, branch, leaf etc. It would be great if someone could provide that detailed picture.

I came across this diagram (i.e. the one showing extension branch & leaf). This diagram seems to be showing details of only one block with multiple transactions. I am looking for a diagram offering similar details but with multiple blocks, each involving multiple transactions.


texts: When a contract calls another contracts, can it return values?

texts:
When a contract calls another contract, are values returned ? I've seen things like:

function foo() external returns (bool success) {
    if( ... ) throw;
    return true;
}

But have read that calls to other contracts return either false if the call fails, or true if the call succeeds, meaning the returns (bool success)and return trueare redundant.


texts: Read more than 32 bytes from memory (Assembly)

texts:
Assume I am passing a variable bytes (memory) to a function. This variable corresponds to A concatenated with B where A is of size 32 and B is 96 bytes, how can I return A (bytes32) and B (bytes).

function readData(bytes memory data) public returns (bytes32, bytes memory){
    bytes32 A;
    bytes memory B;
    assembly{
        A:= mload(add(data,0x20))
        calldatacopy(B,0x45,0xA0) // not sure about this
    }
    return (A,B);
}

Edit

knowing the length of B make things easy but the things is that B size can change, therefore hardcoding a sequence of mload (one per word of data) won't do. this could be solved with an assembly loop but I wonder if there is a more efficient way to do it.


texts: Transaction not propagated or mined on Rinkeby

texts:
I create ETH transactions programatically and send them to the Infura Rinkeby node as rawTransaction. The transaction in questios is accepted by the node, but can't be found by other nodes (Alchemyapi, Etherscan). If I submit the transaction to either of those other nodes they will be accepted there. Only a node where I manually submitted the transaction with sendRawTransaction is able to find the transaction via getTransactionByHash.
From this I'm concluding, that the transaction is not propagated through the network. blockHash and blockNumber will also stay null.
Is it possible to create a transaction that is considered valid by all the nodes, but won't be mined or propagated because it's broken in another way?
This is the raw transaction:
0xf86c81f5851414e68e8082520894cbff0f11f63773f69968782d9b91e97cfcb90b1f87442c11036f0c00802ba0d5d79b07f6927845f0481f5379c1f353d62bcb5597b07774ab324ccb815b73afa07262a3b7c0d9cc8f0145db85d1aa8e8eeac45d4f152497e9f8dc478f07292290


texts:
I want to be able to edit values in a struct.
My struct is declared and mapped like this :

struct entityLinks{
        string linksUrl;
        string linksName;
    }
    mapping (uint => entityLinks) allLinks;

The only matter is that i don't know how to dynamicly select the proper value in my struct. The only way I found was to pass a _targeted argument to manually select the proper property.

   function editEntityLink(uint _entityLinks,uint _targeted,string _content) external onlyOwner() {
            if(_targeted == 1){
                allLinks[_entityLinks].linksName = _content;
            }
            else if(_targeted == 2){
                allLinks[_entityLinks].linksUrl = _content;
            }
        }

I want to be able to have something which fit in 1 line without endless if ...
(Trying to use a string as argument to edit the property don't work)

Thanks , I hope I was clear !


texts: Dapp Communication using smart contract written in solidity in truffle framework

texts: How will two Dapps, developed using truffle framework, will communicate with the contract deployed by one Dapp ( Consider testnet using geth)?


texts: Remix Testrpc "base fee exceeds gas limit"

texts:
I am following this great tutorial from Ed Zynda. I started testrpc and tried to deploy the FuncToken.sol to a Web3 Provider. I managed to connect to the local RPC (have to change protocol from https to http: in order to do it though).

And it prompted me with the error message as follows:

creation of browser/BasicToken.sol:BasicToken pending...
creation of browser/BasicToken.sol:BasicToken errored: Error: base fee exceeds gas limit
    at runCall (/usr/local/lib/node_modules/ethereumjs-testrpc/build/cli.node.js:70875:17)
    at /usr/local/lib/node_modules/ethereumjs-testrpc/build/cli.node.js:12643:24
    at replenish (/usr/local/lib/node_modules/ethereumjs-testrpc/build/cli.node.js:9736:17)
    at iterateeCallback (/usr/local/lib/node_modules/ethereumjs-testrpc/build/cli.node.js:9721:17)
    at /usr/local/lib/node_modules/ethereumjs-testrpc/build/cli.node.js:9696:16
    at /usr/local/lib/node_modules/ethereumjs-testrpc/build/cli.node.js:12648:13
    at /usr/local/lib/node_modules/ethereumjs-testrpc/build/cli.node.js:67073:16
    at replenish (/usr/local/lib/node_modules/ethereumjs-testrpc/build/cli.node.js:67020:25)
    at /usr/local/lib/node_modules/ethereumjs-testrpc/build/cli.node.js:67029:9
    at eachLimit (/usr/local/lib/node_modules/ethereumjs-testrpc/build/cli.node.js:66953:36)

I double checked the account that I was using to deploy, it is within the local test network with a balance of 100 ethers left. I verified it both in Metamask and Remix.

At the same time, I can deploy it successfully both in Javascript VM or Injected Web3. Metamask will ask me verify the fee and submit it, however, when in the Web3 Provider mode, it just errored out without any Metamask popup.

Can you help me understand what I did wrong? At the same time, what does base fee and gas limit mean in this case (I manually changed the Gas Limit to be 3e12 from 3e6 and it did not help)?


texts:
I'd like to store the amount of ether sent to a contract.

I thought I could use the data type 'wei' but apparently that doesn't compile. Ex:

wei public someBalanceVar;
wei public someBalanceVar2;

What is the best way to store value denominated in wei?


texts:
I discover that forks in poa network can happen!

I have 4 nodes (trusted nodes) I want to create a poa network with no forks,
is it possible ?


texts: What big number library does ethers.js use?

texts:
Logging a value from a contract with ethers.js, gets me this:

tokenBalance: v
  _hex: "0x033b2b2062ddfc98de7fffff"
  _ethersType: "BigNumber

Is this an instance of bn.js, bignumber.js or a custom implementation?


texts: The log file created using event is shown below.  Is it possible to show the variable names of the fields that the values are being displayed.


texts: Is it possible to migrate your db(users login credentials) to ethereum private network?

texts: I am thinking of migrating db to any of blockchain technologies for security purposes. I have to opt from hyperledger or ethereum private network. Is it good idea or any trades off I should be aware of.


texts: I just sent ETH to an ICO. tx receipt failed. How can I get my funds back?

texts:
I incorrectly sent Ethereum direct to an ICO address instead of an ERC-20 Compliant wallet.  I can see the transaction has failed however not sure how to recover my funds. Can anybody please help me?

https://etherscan.io/tx/0x06f96d44cc0f97e8b38a0b864e7af9b000b200e3346f9319ba52c3e5bc068aab

Many thanks
NR


texts: Miner.Start not working, unable to mine contract using Nethereum testChain (Geth v1.6.6)

texts:
Been testing Nethereum and attempting to get a basic test class running as per the Nethereum documentation, but having trouble when running the mining command.

I am using Geth v1.6.6
Running the Nethereum testchain via
https://github.com/Nethereum/Nethereum/tree/master/testchain

Issue

Miner.Start was always bringing back "false" to begin with. Then I stumbled on to this question Nethereum 2.0.0-rc5 Miner which mentions that I should try using the pre-release where Web3Geth is the new way to call mining, trying both ways, I am still unable to get a true value to then continue with my test.

var mineResult = await web3Geth.Miner.Start.SendRequestAsync(6);
//var mineResult = await web3.Miner.Start.SendRequestAsync(6);

This is my XUnit test class where the issue is happening.

    using System.Threading;
    using System.Threading.Tasks;
    using Nethereum.Geth;
    using Nethereum.Hex.HexTypes;
    using Nethereum.Web3;
    using Xunit;

namespace BasicTurorial
{
    public class TestClass
    {
        [Fact]
        public async Task ShouldBeAbleToDeployAContract()
        {
            var senderAddress = "0x12890d2cce102216644c59daE5baed380d84830c";
            var password = "password";

            var abi = @"[{""constant"":false,""inputs"":[{""name"":""val"",""type"":""int256""}],""name"":""multiply"",""outputs"":[{""name"":""d"",""type"":""int256""}],""payable"":false,""type"":""function""},{""inputs"":[{""name"":""multiplier"",""type"":""int256""}],""payable"":false,""type"":""constructor""}]";
            var byteCode =
                "0x60606040523415600b57fe5b6040516020806100ac83398101604052515b60008190555b505b6079806100336000396000f300606060405263ffffffff60e060020a6000350416631df4f14481146020575bfe5b3415602757fe5b60306004356042565b60408051918252519081900360200190f35b60005481025b9190505600a165627a7a72305820ec2cf1c300fa92e0ccd1f5ce518cc43c9578fe9007797024f1424d07f491020a0029";
            var multiplier = 7;

            var web3 = new Web3();
            var web3Geth = new Web3Geth();

            var unlockAccountResult =
                await web3.Personal.UnlockAccount.SendRequestAsync(senderAddress, password, 120);

            Assert.True(unlockAccountResult);

            var transactionHash =
                await web3.Eth.DeployContract.SendRequestAsync(abi, byteCode, senderAddress, multiplier);

            var mineResult = await web3Geth.Miner.Start.SendRequestAsync(6);
            //var mineResult = await web3.Miner.Start.SendRequestAsync(6);

            Assert.True(mineResult);

            var receipt = await web3.Eth.Transactions.GetTransactionReceipt.SendRequestAsync(transactionHash);

            while (receipt == null)
            {
                Thread.Sleep(5000);
                receipt = await web3.Eth.Transactions.GetTransactionReceipt.SendRequestAsync(transactionHash);
            }

            var contractAddress = receipt.ContractAddress;
            var contract = web3.Eth.GetContract(abi, contractAddress);

            var multiplyFunction = contract.GetFunction("multiply");

            var result = await multiplyFunction.CallAsync<int>(7);

            Assert.Equal(49, result);
        }
    }
}

Full sourcecode can be found here https://github.com/stradled/NethereumTest


texts: How much control does Consensys have over Ethereum, and how does this affect Ethereum's decentralization?

texts:
Sometimes I wonder about things like this:

The DAO was responsible for the generation of Ethereum Classic. This gave anyone who had invested in Ethereum prior to the fork a major investment boost.
The DAO was funded primarily Consensys. Consensys was founded by Joe Lubin, a former Goldman Sachs banker, and the main investor of Ethereum. He probably held close to 40% of the Ether within the genesis block of Ethereum at the time of the fork. You could never prove this, because blockchains are anonymous. But anyone familiar with the industry knows how centralized the crowdsale really was, and more importantly, how long these coins remained unmoved.
When Ethereum forked, Consensys and Joe profited way more than anyone else. Because they had coins in the genesis block, they now had just as much of both Ethereum and Ethereum Classic, effectively doubling their investment.
Consensys then created a business offering for "smart contract audits". Again profiting off the hack of their own system.
Consensys remains the primary blockchain consulting company for smart contract audits. Not only does this allow them to charge fees, but it allows them to fully understand the intellectual property of blockchain startups before their product is released.

We know that Vital talks of unnamed people in the early days of Ethereum "only wanting to make a big pile of money". If your personal mantra is that "financial incentives are everything", then you can't deny that all the above bullets correspond to Joe and Consensys's logical course of action. That can still be your mantra, if you're okay with giving them enough wealth to move entire markets without you getting a say.

We also know that that Casper is most likely named after "Casper the friendly ghost", meaning it's basically ghostware meant to hold up Ethereum's price. Even if it's released mid-2019 (not sure why anyone would believe that), it's still ghostware for being two years late.

Why should you care about any of this? Because cryptocurrency is the last bastion for humanity to undo the planet-destroying, wealth-pyramidizing effects of Joe Lubin's generation. People like to talk down to populists like me and say "that isn't the way the world works" -- I'm saying, with a programmed economy, there's no reason it can't be. Nash's theory of equilibrum proves it. It amazes me how any community could cling to the word of a 55+ white dude as if he's the one who's going to build an internet currency that finally catches on. He dropped over a million dollars in Civil lol.

Vital is cool, if only temporarily corrupted by Joe. Ethereum's code is great, and so is the code put out by Consensys. But Joe Lubin's snakeoil speak, and the intitial distribution of Ethereum's coin, are two very good reasons to seek out other blockchain projects.

Can anyone give a good reason how Consensys's control over Ethereum's markets allows for true decentralization?


texts: How do I capture a smart contract function return values when changing the contract status?

texts:
pragma solidity ^0.4.6;

contract Demo {

    uint a;

    function set(uint b) returns (uint) {
        a = b;
        return a * b;
    }

    function get() constant returns (uint) {
        return a;
    }
}

Q: The function "get()" is a constant function, it is not changed the contract status, it just return the "a" value, when the function "set(uint b)" called, it will return a transaction hash, and wait to the mined, so then, how to capture the return value "a * b" ?
Many blogs and answer say it can't captured, but use event can do this, But a online compiler can do this, https://ethereum.github.io/browser-solidity , and how the browser-solidity did it ?


texts:
I am trying to comprehend the following snippet of payment code:

        if (collectedFees >= minFeePayout) {
            if (!owner.send(collectedFees)) {
                // Potentially sending money to a contract that
                // has a fallback function.  So instead, try
                // tranferring the funds with the call api.
                if (owner.call.gas(msg.gas).value(collectedFees)()) {
                    collectedFees = 0;
                }

The code fragment is from this contract: https://etherscan.io/address/0x9f1d916a456b96146e9f0dbbd0e107a1f389a061#code.

So my question is:

why this contract uses one send and one call?
Is it safe? I am using some security tools to check this contract and somehow this part is flagged as "vulnerable". I just don't get it.


texts: Integrate web3.js into a native iOS & Android Apps

texts:
Integrating web3.js into a native iOS & Android Apps has issues.

I am having difficulty integrating web3.js into a native mobile App (iOS & Android), would it be reasonable to use a cloud server & npm install web3 and let the mobile App connect to that Cloud server instance to make all calls to a deployed Smart Contract?

The only issue I see with this, is that it defies the peer-to-peer architecture of the blockchain by having a cloud server in the middle.


texts: I have seen that nodes hold a storage trie and state trie. What are those tries and are there these two tries per a contract code (in every copy of the blockchain)?


texts: Adjust slippage tolerance in Uniswap programatically

texts:
I've been able to do swaps through Uniswap's peripheral smart contract Router 02 by calling any of the functions such as:
function swapTokensForExactTokens(
  uint amountOut,
  uint amountInMax,
  address[] calldata path,
  address to,
  uint deadline
) external returns (uint[] memory amounts);

However, none of these functions has any field referring to the slippage (amount the price moves in a trading pair between when a transaction is submitted and when it is executed), and I don't know exactly at which stage the slippage is set before launching the swap transaction.
Is there any way to handle the slippage tolerance programatically when executing a swap transaction?


texts: how do storage and memory variable work?

texts:
So, in an ordinary programming language, we have stack and heap.
Reference types such as array gets stored in heap. and the variable which holds the address(pointer) of this array is stored in stack..
Question 1) what about solidity's memory ? when array gets created in memory, does solidity store the pointer of that array in stack ?
Question 2) what about solidity's storage ? I think in this case, since it's persisent, stack doesn't come into play. so where is the pointer of the array(stored in storage) stored ?


texts: contract.method.balanceOf() is not a function

texts:
Update 1: When I console.log() the imported contract, it turns out that my contract does not have any methods. What could be the issue?
I am working on a functionality where it checks the balance of a customized token of an account. The token comes from the following pre-made solidity contract. This contract is just a duplicate of ERC20 with same name changes.
import healthToken from './healthToken';'

And this is how I try to get the balance:
    const balance = await healthToken.methods.balanceOf(this.walletAddress).call();

However, when I test this, it shows the following error:

I have checked the contract and am sure that balanceOf is a function, what is causing the error?


texts: Why is it that my first original contract containing the setters and gettters are not showing up when I hit deploy?

texts:
pragma solidity ^0.4.24;

contract Bank{
    uint private value;

    constructor(uint amount) public{
        value = amount;
    }
    function deposit(uint amount) public{
        value += amount;
    }

    function withdraw(uint amount) public{
        value -= amount;
    }

    function balance()view public returns (uint){
        return value;
    }
}

contract MyFirstContract is Bank(10){
    string private name;
    uint8 private age;

    function setName(string _name) public {
        name = _name;
    }

    function getName()view public returns(string){
        return name;
    }

    function setAge(uint8 _age) public{
        age = _age;
    }

    function getAge() view public returns (uint8){
        return age;
    }

}


texts: Do contract calls atomically modify contract contents?

texts:
Suppose a contract has the following:

uint[] arr;

function func(int a, int b) {
    arr.push(a);
    arr.push(b);
}

If two clients call func at essentially the same time with (1, 2) and (3, 4), are the contents of arr guaranteed to be in the order of the calls?

You would expect the order of modifications to be something like:

// contract.func(1, 2) call #1
arr.push(1); // #1
arr.push(2); // #1
// contract.func(3, 4) call #2
arr.push(3); // #2
arr.push(4); // #2
// arr = [1, 2, 3, 4]

However, is it possible that the execution of events are interleaved as such:

// contract.func(1, 2) call #1
// contract.func(3, 4) call #2
arr.push(1); // #1
arr.push(2); // #2
arr.push(4); // #2
arr.push(3); // #1
// arr = [1, 2, 4, 3]

Thank you.


texts:
quorum-wizard Quickstart option is failing with error.
Downloading dependencies...
Using cached quorum at: /Users/vivart/.quorum-wizard/bin/quorum/20.10.0/geth
Using cached tessera at: /Users/vivart/.quorum-wizard/bin/tessera/20.10.0/tessera-app.jar
Using cached cakeshop at: /Users/vivart/.quorum-wizard/bin/cakeshop/0.11.0/cakeshop.war
Building network directory...
Generating network resources locally...
Building qdata directory...
Initializing quorum...
(node:2203) UnhandledPromiseRejectionWarning: Error: Command failed: cd '/Users/vivart/network/3-nodes-quickstart' && '/Users/vivart/.quorum-wizard/bin/quorum/20.10.0/geth' --datadir 'qdata/dd1' init 'qdata/dd1/genesis.json' 2>&1
    at checkExecSyncError (child_process.js:616:11)
    at execSync (child_process.js:652:15)
    at executeSync (/usr/local/lib/node_modules/quorum-wizard/src/utils/execUtils.js:5:10)
    at forEach (/usr/local/lib/node_modules/quorum-wizard/src/generators/bashHelper.js:31:37)
    at Array.forEach (<anonymous>)
    at initBash (/usr/local/lib/node_modules/quorum-wizard/src/generators/bashHelper.js:31:16)
    at createDirectory (/usr/local/lib/node_modules/quorum-wizard/src/index.js:128:11)
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
    at generateNetwork (/usr/local/lib/node_modules/quorum-wizard/src/index.js:112:3)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:2203) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
(node:2203) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.


texts: Remix - Contract A doesn't work anymore when I deploy contract B

texts:
I recently had to deploy my second contract on the local Ganache Blockchain (Windows) using http://remix.ethereum.org/.

But every single time I deploy contract B after I deployed contract A, contract A doesn't work anymore. No returns - nothing.

I really need both of the contracts to communicate with them and between.

Anyone else had the same issue or knows how to solve the problem? Thanks

PS: I'm using some of the openzeppelin libraries and get them via. a remote connection using the command "remixd -s "PATH"

Code to reproduce:

  test2.sol

pragma solidity ^0.4.24;

contract test2 {
    uint value = 1338;

    function getSender() public view returns(uint) {
        return value;
    }

    function setValue(uint _value) public {
        value = _value;
    }
}

  test.sol

pragma solidity ^0.4.24;

contract test {
    uint value = 1337;

    function getSender() public view returns(uint) {
        return value;
    }

    function setValue(uint _value) public {
        value = _value;
    }
}

When I deploy testCoin.sol and then deploy test.sol I cant access any function the testCoin.sol contract provides. The console says "call to testCoin.balanceOf" - that's all. No return, no message - simply nothing.


texts: What explains ETH appreciation spikes over Bitcoin? Historical price chart analysis

texts:
The green line in the chart above shows Ether appreciating heavily over Bitcoin from Feb to July 2017 from 0.03 to 0.14 ETH/BTC (288% appreciation over BTC). Is this some sort of mistake, equivalent to the disparate appearance of stock splits on charts? If viewing the BTC chart on its own (not shown), there doesn't seem to be a whole lot of negative activity on the BTC chart that would suggest an altcoin like ETH is exploding over it. Even the ETH chart (the black line above), is rather modest compared to the green appreciation for this Feb-Jul 2017 segment.
This run-up occurs a second time in early 2018, extending past Bitcoin's December 2018 peak of near-$20k that we all remember.

Except this spike for Ethereum coincides with its actual price (green
line is on top of the black line),
whereas ETH's spike in 2017 highly outgrossed its price (green line
way above the black line).

What explains this two different dynamics observed? What was really happening that made the spikes so different?


texts: Is this smart contract possible to make?

texts:
I want to make a smart contract that will give me an upper edge when it comes to buying into icos. Basically once a condition is met, for example the block reaches a certain number or a specific date requirement is met all the eth in a wallet will be sent to the pre coded wallet address.

I'ts a fairly simple idea but was wondering if something like this is what smart contracts were made to do. A simple yes or no and maybe a pointer is more than enough, I'll figure out how to make it on my own. I know Python 3 and Java, I know smart contracts are coded in JS which is pretty close to Java so I shouldn't have a problem figuring this out.


texts:
I am reading the solidity docs but there is a part I don't really understand.

In this example:

pragma solidity ^0.4.0;

contract C {
    uint someVariable;
    uint[] data;

    function f() public {
        uint[] x;
        x.push(2);
        data = x;
    }
}

the doc says that "The type of the local variable x is uint[] storage, but since storage is not dynamically allocated, it has to be assigned from a state variable before it can be used."

I don't really understand what does it mean by "storage is not dynamically allocated" and why the method "x.push(2)" does change the "somevariable"

Any help is appreciated.


texts: Is there any way to integrate ERC20 token as payment to ecommerce

texts: If want to integrate ERC20 token to integrate as paymen to a website. how can?


texts: Work with local copy of Ropsten without syncing

texts: I have used Geth to successfuly download (and sync) with Ropsten network. Is it possible to use downloaded blockchain (reading blocks with Geth) without syncing with Ropsten? I would basically like to read what I have in local with get, without obtaining new blocks. Is this possible?


texts: Do we have to compile and deploy our contract to ethereum each time we start a test rpc?

texts: I'm trying to develop a voting application, I have successfully compiled the app and also deployed it to ethereum blockchain. Now I've closed the test rpc and node console, and when I restarted node console and test rpc my app was not performing as it should be, then I compiled it again and deployed again and it is now working good. So, I was asking do we have to compile and deploy our app every time we start the test rpc? If yes is there any way for my app to run all the time so I don't have to repeat the process of compiling and deploying it again and again.


texts:
I am stuck on this little problem in my chat app smart contract(this is only the faulty piece of code)
contract ChatApp {
        struct user{
            bool acceptReq;
            uint nreq;
            address[] requests;
            address[] friends;
        }
        mapping(address  => user)  _users;

        function sendreq(address friend) public returns(string memory){
            //_users[friend].requests[_users[friend].nreq]=msg.sender;
            _users[friend].requests[0]=msg.sender;
            return "this function has been executed properly";
        }
}

The problem that I'm facing is that when I execute the function sendreq(), the IDE throws this error
VM error: invalid opcode. invalid opcode

I think that the problem is somewhere in the mapping but I can't find it.
Can you guys help me?


texts: Minereum Lucky Draw claims 100% Safe randomness on a smart contract without oracles, is it really possible?

texts:
Is the way Minereum Lucky Draw game works really safe 100% onchain RNG and verifiable on smart contract?
They claim yes but I would like to know expert technical answer for this, if so, isn't this a major breakthrough in generating random numbers on the blockchain without oracles?
More details: https://www.minereum.com/v2/luckydraw
They say:

The Random Number Generation is totally decentralized and fair, the source code can be verified here. The random numbers are generated based on the blockhash of the second block after purchase. There is an interval of 3 blocks between buying a ticket and playing to be able to guarantee complete unpredictable randomness 100% on-chain.


texts: Network propagation delay and forks in Proof of Stake?

texts:
I am learning the fundamental of Proof of Stake (PoS), i came accross a question which i could not find answer to. Assume we have three validators (aka miners in PoW), V1, V2 and V3. Each of the validators controls 1/3 of the total stake? If PoS is designed to have a block generated each 5 seconds. at time=5 V1 was assigned to generate a block B1 and send it to other verifiers. Due to propagation delay, V2 was assigned to generated B2 at time =10, but at that time he has not received B1 yet .

In PoW, V2 will generate another version of B1 "a competitive block", so this refers to a fork, and at the end either V1 or V2 will win the block.

My question, does this will be the case for PoS? if not, how it works then?


texts: As of today (Solidity v0.4.22)... Is there a way to return structs from public functions?

texts:
https://medium.com/coinmonks/solidity-tutorial-returning-structs-from-public-functions-e78e48efb378

According to this article (link above), on Medium I'd have to use tuples... but this was so in Solidity v0.4.13 is possible now in v0.4.22 to do it without using tuples? Or do I still have to use tuples?
I've also seen an method that uses "experimental ABIEncoder" so is there a better way... what options are there to return structs from public functions ?


texts: Call a Contract With Web3JS/ethereumjs-tx

texts:
I want to execute a smart contract on the blockchain. As far as I understood this web3js offers two options

call: executes the contract method locally without using gas
execute: executes the contract method on the blockchain and requires gas

What I don't get how to use a specific wallet e.g.

const ABI = require('./contracts/abi.json');
const addressContract = "xyz";
const Web3 = require('web3');
const Tx = require('ethereumjs-tx');

const wallet = {
  public: somePublicKey,
  private: somePrivateKey
}

const web3 = new Web3(new Web3.providers.HttpProvider(config.provider));
const contract = new self.web3.eth.Contract(ABI, addressContract);
const options= {
    from: wallet.public,
    gasPrice: process.env.GAS
    gasLimit: 250000

  }
contract.methods.methodA(param1,param2,param3).send(options, (err, txHash)=> {
  console.log("err",err)
  console.log("txHash",txHash)
})

I found that to execute a contract there is a plugin called ethereumjs-tx which would modify my code to the following:

//options.data = ?
options.to = addressContract
options.nonce = someNonce
const tx = new Tx(options);
tx.sign(new Buffer(wallet.private, 'hex'));
const rawTx = `0x${tx.serialize().toString('hex')}`;
self.web3.eth.sendRawTransaction(rawTx, (err, result) => {
  console.log("err",err)
  console.log("txHash",txHash)
});

I'm struggling basically with the data property. Because contract.methods.methodA.getData does not exists.

Question

1) How to get my params into the data format? / Or do I just add them to options instead of options.data

EDIT: I guess I could feed all the params into:
https://github.com/ethereumjs/ethereumjs-abi

var parameterTypes = ["address", "uint256", "address", "uint256", "uint256", "uint256", "address", "uint8", "bytes32", "bytes32", "uint256"];
var parameterValues = ["0x1234567812345678", 256, "0x1234567812345678", 256, 256, 256, "0x1234567812345678", 8, 32, 32, 256];

var encoded = abi.rawEncode(parameterTypes, parameterValues);

And attach the result to data with '0x'+encoded.

useful links

docs


texts: Can you have an array of mappings? The mappings have an address key and a struct value

texts:
Can you have an array of mappings?
I want to have mappings with addresses as keys and structs as the value.
I want to store these addresses in an array and iterate through them.
so far it looks like this how would I modify this?

pragma solidity ^0.5.0;

contract Ranking{

    struct User {
      string name;
      uint level;
    }

    mapping (address => User) userStructs;
    address[] public userAddresses;

    function createUser(string name, uint level) {
      userStructs[msg.sender].name = name;
      userStructs[msg.sender].level = level;
      userAddresses.push(msg.sender);
    }

    function getAllUsers() external view returns (address[]) {
      return userAddresses;
    }
}


texts: How to interact with a BSC contract using Python

texts:
Binance Smart Chain. I've first tried sending a transaction with python:
from web3 import Web3

transaction = {
        'chainId': 97,  # 97: Testnet. 56: main.
        'to': '0xmyaddress',
        'value': 1,
        'gas': 2000000,
        'gasPrice': 13,
        'nonce': 0,
    }

infura_url = "https://mainnet.infura.io/v3/my-api-key"
w3 = Web3(Web3.HTTPProvider(infura_url))

key = '0xmykey'
signed = w3.eth.account.signTransaction(transaction, key)

w3.eth.sendRawTransaction(signed.rawTransaction)

Giving me the following error: ValueError: {'code': -32000, 'message': 'invalid sender'}

Now, I am trying to interact with a contract - calling methods and giving inputs, but I am unsure how to accomplish this.


texts: Listening for Deposits and Transaction Confirmations Web3js

texts:
I'm building a webapp using nodejs and web3js. I have a simple use-case: I provide the user with an address to which he should deposit funds. I want to then listen on my nodejs server for:

when the user deposits funds to this address
the transaction which deposits these funds has gone through 12 confirmations.

I know I can check the balance of the account using:

var balanceWei = web3.eth.getBalance(walletAddress).toNumber();

however this is not enough in my use case. I need to know when a transaction occurs which deposits funds into this account, as well as when this transaction is confirmed so that I can make these funds available to the user within my app.


texts: what is the functionality of use of "Airdrop" in smart contract, have seen many where result pop-up "adding airdrop in already deployed smart contract" as far as my knowledge once smart contract is deployed can't make any change so how "Air Drop" can be added as a functionality ?


texts:
When installing wallet + mist v0.8.3 you see something like this:

What is meant by "chain structure"? Is the "222 of 4446" just a download progress indicator or does each single part have a meaning?


texts: What does scope do in the function itself?

texts:
Here is one of the functions I am curious about...
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock {
    require(amount0Out > 0 || amount1Out > 0, 'UniswapV2: INSUFFICIENT_OUTPUT_AMOUNT');
    (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
    require(amount0Out < _reserve0 && amount1Out < _reserve1, 'UniswapV2: INSUFFICIENT_LIQUIDITY');

    uint balance0;
    uint balance1;
    { // scope for _token{0,1}, avoids stack too deep errors
        address _token0 = token0;
        address _token1 = token1;
        require(to != _token0 && to != _token1, 'UniswapV2: INVALID_TO');
        if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens
        if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens
        if (data.length > 0) IUniswapV2Callee(to).uniswapV2Call(msg.sender, amount0Out, amount1Out, data);
        balance0 = IERC20(_token0).balanceOf(address(this));
        balance1 = IERC20(_token1).balanceOf(address(this));
    }
    uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0;
    uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0;
    require(amount0In > 0 || amount1In > 0, 'UniswapV2: INSUFFICIENT_INPUT_AMOUNT');
    { // scope for reserve{0,1}Adjusted, avoids stack too deep errors
        uint balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3));
        uint balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3));
        require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(1000**2), 'UniswapV2: K');
    }

    _update(balance0, balance1, _reserve0, _reserve1);
    emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to);
}

As you can see, if you search for the comment // scope for token...., you will see there's another { in there.
I am wondering why it is there and what purpose it serves..
UPDATE:
pragma solidity ^0.4.24;
contract TestStackError {
  event LogValue(uint);
  function logArg(uint a1, uint a2, uint a3, uint a4,
    uint a5, uint a6, uint a7, uint a8,
    uint a9, uint a10, uint a11, uint a12,
    uint a13, uint a14, uint a15
  ) public {

      {
        uint a16 = 1;
        uint a17 = 2;
      }

  }
}

Why does it still say stack to deep error even though I intruduced another {} scope ?


texts: Is there length limits on Token Symbols?

texts: Is there a limit on the length of a ERC20 Token symbol?  I would like to use 4 letters, one of which is lower case, but that isn't an issue.  My concern is if Exchanges have setup their tools to only handle 3 letters which is what most are today.


texts: Do parts of decentralised apps take advantage of centralisation?

texts:
So, obviously MetaMask interacts with public, distributed ledgers in order to show my balances, however, from a technical perspective, do certain parts of the application use centralised databases? Such as storing my user preferences (current set language/locale etc)?
If so, is it possible to create a truly decentralised application which stores all things in a decentralised way, or would this simply not work as I'd have to wait for a transaction to complete each time I saved my profile? I guess UniSwap would be another good example, are ALL parts of the ecosystem run in a decentralised way, or just the swapping aspect?
I guess a DAO (not THE DAO) would be a better example, as, surely ALL parts of the ecosystem would have to be run and stored in a distributed way in order for it to be a fully autonomous.. or maybe my limited understanding in terms of DAO structures, and how data storage and transactions work on Ethereum is incorrect here.


texts: Easiest way to call an implementation function from a proxy contract in Remix

texts:
I have the following code in my remix.ethereum.org project:
pragma solidity ^0.6.10;

// SPDX-License-Identifier: Unlicensed

import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/proxy/UpgradeableProxy.sol";

contract ImplementationContract {
    function returnTen() public pure returns(uint) {
        return 10;
    }
}

contract ProxyContract is UpgradeableProxy {
    constructor(address _logic, bytes memory _data)
        UpgradeableProxy(_logic, _data)
        public
    {
    }
}

I've used Remix to deploy both contracts to the JavaScript VM.
Now what is the easiest way to call returnTen() from the ProxyContract deployment?


texts: Is there a way to read data from smart contract using PHP?

texts: I have a smart contract. All what I need is to make a PHP script that will get some public data from smart contract using it's address. How can I do that? Maybe there is some libraries?


texts: Isolating the EVM and calling contracts functions

texts:
For a project of mine I would like to run a standalone new EVM with precise specifications.
After having instantiated and set up the vm, I have a deployed a test contract using the vm « Create » function.

However I don’t understand how to invoke specific methods of the contract using go-ethereum.

I thought I could use the Call and CallCode functions but they don’t indicate any argument concerning the methods except the input byte array.

Any help really appreciated,

Thanks


texts: How to send ether to a contract when deploying the contract?

texts:
I have a contract like the following:

contract HoneyPot {

  mapping (address => uint) public balances;

  function HoneyPot() payable {
    balances[msg.sender] = msg.value;
  }

}

When deploying the contract I want to send some ether so the balances[msg.sender] for the account deploying the contract gets a balance equal to the amount of ether sent. How should this be done?

Here is how I am deploying the contract:

const fs = require("fs");
const solc = require('solc');
let Web3 = require('web3');
let web3 = new Web3();
web3.setProvider(new web3.providers.HttpProvider('http://localhost:8545'));
let go = fs.readFileSync('HoneyPot.sol').toString();
let compiledContract = solc.compile(go);
abiDefinition = JSON.parse(compiledContract.contracts[':HoneyPot'].interface);
contract = web3.eth.contract(abiDefinition);
byteCode = '0x'+compiledContract.contracts[':HoneyPot'].bytecode;
let gasEstimate = web3.eth.estimateGas({data: byteCode});

And finally the line that deploys it (without sending ether):

deployedContract = contract.new({from:web3.eth.accounts[0],data:byteCode,gas: gasEstimate+40000});


texts: how come i can generate keys using bip39 with only one words as seedphrase/mnemonic without any error?

texts: Seed phrase/mnemonic is supposed to be 12 words or 24 words but I am able to generate keys with single word seed phrase using bip39 library without any error? what is happening here? how is this possible?


texts: address.send() returns 'true' but transaction doesn't happen

texts:
I am trying to send ether from a contract to another address. I used the send method do that. The function returned true but the transaction didn't happen at all. The contract definitely has a lot of balance in it.

Here is my contract code.

contract Betting {

  address public ac2 = 0xCB87BDB88EEF4ABC66AE6F1A131D41021C145863;
  address public myaccount = this;
  bool public transferStatus = false;

  event Transfer(address _from, uint256 _value);
  event TransferTo(address _to, uint256 _value);

  function Betting() {

  }

  function sendEther() payable returns (uint) {
    return msg.value;
  }

  function () payable {
   Transfer(msg.sender, msg.value);
  }

  function reward() payable returns (bool) {
    transferStatus = ac2.send(0.05 ether);
    TransferTo(ac2, 0.05 ether);
    return transferStatus;
  }

Edit: I found that transactions that are called from within a contract will be stored as internal transactions. Interestingly, My contract doesn't even have an internal transaction tab in Etherscan


texts: When sending a TX, there's an optional gasPrice field. If I don't set it, what's it default to? Does it look at other TXs going on or is it a fixed value that only changes when web3 gets updated to a new version? Is there a way to get the default value so that I can, for example, add 1gwei to it? I'd like to ensure order of TXs in the same block by paying more for the first TX.


texts: Will the parameters in the smart contract function be exposed?

texts:
A function in the smart contract needs to accept parameters to execute. If I pass this parameter to the contract, but don’t save the parameter on the chain, is it theoretically transparent on the blockchain? Everyone can do it See the value of this parameter.
Is there any way to hide the value of a parameter in a smart contract?
Hopes you can give me some help, thanks!