#StackBounty: #solidity #unittesting #msg.sender Using different accounts for executing a function in solidity unit testing

Bounty: 100

I have written a smart contract and within which I have declared a payable function where everyone could send their funds to the contract. Once they have transferred their funds, they would have the allowance to use some other features. However, now I want to write a solidity unit test for the script to test its functions when different accounts send funds through. I wanted to know whether there is any way to modify the msg.sender while executing functions of solidity unit testing. For instance, account 1 sends eth to contract, then account 2 needs to do the same.


Get this bounty!!!

#StackBounty: #solidity #testing #hardhat Testing an event with a timestamp arg

Bounty: 50

I’m trying to write a test using waffle, but I’m not sure how to assert that a timestamp is correct in an emitted event.

My event looks like this:

event BeginJourney (
    uint256 indexed departFrom,
    uint256 indexed arriveAt,
    uint256 indexed arrivalTime
);

which is emitted like this in the contract:

emit BeginJourney(currentId, newId, block.timestamp + travelTime);

My test so far looks like this:

await expect(city.connect(acc1).travelTo(1))
    .to.emit(city, "BeginJourney").withArgs(0, 1, ???);

Using Waffle’s .withArgs assertation, I can only check exact values. What I really want is to check that the 3rd timestamp arg is within a few seconds of the current epoch time plus some constant.

Is there any way to code this test?


Get this bounty!!!

#StackBounty: #solidity #truffle #truffle-migration #truffle-deployment #migration Issue while migrating to Ropsten network

Bounty: 50

I am trying to migrate the contract to ROPSTEN network. It fails for the following reason. Please advice.

migrate command

$env:MNEMONIC=' XX XX XX';truffle migrate --reset --network ropsten 

Error

Error: There was a timeout while attempting to connect to the network at undefined.
   Check to see that your provider is valid.
   If you have a slow internet connection, try configuring a longer timeout in your Truffle config. Use the networks[networkName].networkCheckTimeout property to do this.
at Timeout._onTimeout (C:UsersskmsuAppDataRoamingnpmnode_modulestrufflebuildwebpack:packagesproviderindex.js:57:1)
at listOnTimeout (internal/timers.js:557:17)
at processTimers (internal/timers.js:500:7) 

truffle-config.js

require('dotenv').config();
const HDWalletProvider = require('truffle-hdwallet-provider'); 

console.log('ab - from powershell file process.env.MNEMONIC : '+     
 process.env.MNEMONIC);

const infuraProvider = network => providerWithMnemonic( 
process.env.MNEMONIC || '',
`https://${network}.infura.io/${process.env.INFURA_API_KEY}`
);
const providerWithMnemonic = (mnemonic, rpcEndpoint) =>
new HDWalletProvider(mnemonic, rpcEndpoint);

module.exports = {

  // See <http://truffleframework.com/docs/advanced/configuration>
  // to customize your Truffle configuration!

  networks: {

development: {
  host: 'localhost',
  port: 8545,
  network_id: '*', // eslint-disable-line camelcase
} , 

mainnet: {
  provider: infuraProvider('mainnet'), 
  gasPrice: 10000000000,  // 10 Gwei
  gas: 4000000,
  network_id: '1'
}, 
ropsten: { 
  provider: infuraProvider('ropsten'), 
  gasPrice: 1000000000,  // 1 Gwei
  gas: 4000000,
  network_id: '3' 
} 
  },

  solc: {
optimizer: {
  enabled: true,
  runs: 200
}
  } 

};


Get this bounty!!!

#StackBounty: #solidity #contract-development #chainlink #randomness Testing Chainlinks Verifiable Random Function call from another co…

Bounty: 100

Locally testing Chainlinks VRF

While trying to locally test a contract that calls a Chainlink VRF contract, I’m experiencing some difficulties in setting up the contract balances. I have a CallChainlink contract that calls the ChainlinkVRF contract. They are initialised (and tested) using the following Waffle test:

Test Code

import {expect, use} from 'chai';
import {Contract, utils, Wallet} from 'ethers';
import {deployContract, deployMockContract, MockProvider, solidity} from 'ethereum-waffle';

import IERC20 from '../build/IERC20.json';
import CallChainlink from '../build/CallChainlink.json';
import SomeOtherContract from '../build/SomeOtherContract.json';
import ChainlinkVRF from '../build/ChainlinkVRF.json';

use(solidity);

describe('Am I Rich Already', () => {
    // Declare contracts
    let mockERC20: Contract;
    let callChainlink: Contract;
    let someOtherContract: Contract;
    let chainlinkVRFContract: Contract;
    
    // Declare wallets
    let mockWallet: Wallet;
    let callChainlinkWallet: Wallet;
    let someOtherWallet: Wallet;
    let chainlinkVRFWallet: Wallet;

    beforeEach(async () => {
        
        // generate random wallets or random origin 
        //const [mockWallet, callChainlinkWallet, someOtherWallet, chainlinkVRFWallet] = Wallet.createRandom();
        //const original = Wallet.createRandom();
        
        // specify wallet balances
        const provider = new MockProvider(
            {
                ganacheOptions: {
                    // The private key is used to generate the four respective wallet addresses.
                    accounts: [
                        {balance: '168626800000000000000001', secretKey: '0x706618637b8ca922f6290ce1ecd4c31247e9ab75cf0530a0ac95c0332173d7c1'}, 
                        {balance: '168626800000000000000002', secretKey: '0x706618637b8ca922f6290ce1ecd4c31247e9ab75cf0530a0ac95c0332173d7c2'}, 
                        {balance: '168626800000000000000003', secretKey: '0x706618637b8ca922f6290ce1ecd4c31247e9ab75cf0530a0ac95c0332173d7c3'},
                        {balance: '168626800000000000000004', secretKey: '0x706618637b8ca922f6290ce1ecd4c31247e9ab75cf0530a0ac95c0332173d7c4'}
                    ]
                }
            }
        );
        
        [mockWallet, callChainlinkWallet, someOtherWallet, chainlinkVRFWallet] = provider.getWallets();
        mockERC20 = await deployMockContract(mockWallet, IERC20.abi);
        someOtherContract = await deployContract(someOtherWallet, SomeOtherContract, [mockERC20.address]);
        chainlinkVRFContract = await deployContract(chainlinkVRFWallet, ChainlinkVRF);
        callChainlink = await deployContract(callChainlinkWallet, CallChainlink, [chainlinkVRFContract.address]);
    });

    // custom test in AskRoot contract
    it('checks callChainlink address is returned correctly', async () => {
        expect(await callChainlink.getAddressThis()).to.be.equal('0x82A666453d8aa239eEBE4578E83cD0988D62c83F');
        
        // This test fails, so the contract address is different than the accompanying wallet addres.
        //expect(await callChainlink.getAddressThis()).to.be.equal(callChainlinkWallet.address);
    });
    
    
    
    // custom test in AskRoot contract
    it('checks callChainlinkWallet address balance is returned correctly', async () => {
        expect(await callChainlink.getAddressThisBalance()).to.be.equal(9001);
    });
    
    
    // custom test in VRF contract
    it('checks someOtherContract wallet address is returned correctly', async () => {
        expect(await someOtherContract.getAddressThis()).to.be.equal('0x63E505e173BdbdD1b5DDB39dfAD716ed150e3466');
    });
    
    // custom test in AskRoot contract for SolveRoot Contract
    it('checks callChainlink calls a function from SolveRoot correctly and returns the right answer', async () => {
        //expect(await callChainlink.callHelloWorld(await someOtherContract.getAddressThis())).to.be.equal('hello World');
        //expect(await callChainlink.callHelloWorld('0x63E505e173BdbdD1b5DDB39dfAD716ed150e3466')).to.be.equal('hello World');
        //expect(await callChainlink.callHelloWorld("0x63E505e173BdbdD1b5DDB39dfAD716ed150e3466")).to.be.equal('hello World');
        expect(await callChainlink.callHelloWorld(someOtherContract.address)).to.be.equal('hello World');
    });
    
    
    // custom test in AskRoot contract for SolveRoot Contract
    it('checks someOtherContract calls a function from SolveRoot correctly', async () => {
        //await token.balanceOf(wallet.address)
        //await callChainlink.callHelloWord(someOtherWallet.address)
        await callChainlink.callHelloWorld("0x63E505e173BdbdD1b5DDB39dfAD716ed150e3466")
        expect('helloWorld').to.be.calledOnContract(someOtherContract);
    });
    
    
    // custom test in AskRoot contract for VRF contract
    it('checks callChainlink calls a function from VRF Contract correctly and returns the right answer', async () => {
        expect(await callChainlink.callHelloUniverse(chainlinkVRFContract.address)).to.be.equal('hello Universe');
    });
    
    
    // custom test in AskRoot contract for VRF contract
    it('checks someOtherContract calls a function from VRF Contract correctly', async () => {
        await callChainlink.callHelloUniverse(chainlinkVRFContract.address)
        expect('helloUniverse').to.be.calledOnContract(chainlinkVRFContract);
    });
    
    
    // custom test in AskRoot contract for VRF contract
    it('checks callChainlink calls a function from VRF Contract correctly and returns the a Uint16', async () => { 
        expect(await callChainlink.callUintSmallSquareFromVRFContract(chainlinkVRFContract.address)).to.be.equal(144);
    });
    
    
    // custom test in AskRoot contract for VRF contract
    it('checks someOtherContract calls a function from VRF Contract correctly', async () => {
        await callChainlink.callUintSmallSquareFromVRFContract(chainlinkVRFContract.address)
        expect('returnSomeSquare').to.be.calledOnContract(chainlinkVRFContract);
    });
    
    
    // custom test in AskRoot contract for VRF contract
    it('Check if a Uint16 can be read from the VRF contract.', async () => { 
        expect(await callChainlink.getVal()).to.be.equal(144);
    });
});

Test results

I verified these pairs of contracts work in Remix, by manually transfering some Kovan network test Eth to the address of the deployed CallChainlink address, and by transfering 2 LINK to the address of the deployed ChainlinkVRF contract. However, the balances of the respective wallets is 0 instead of 168626800000000000000001 once run the Wallet addresses, and I do not exactly know how to to set a LINK balance on the contracts that are created using Waffle.

Question

Hence I would like to ask: How can I set the wallet balances in Kovan test Ethereum and LINK in Waffle such that I can run the tests and CI without requiring manual action?


Get this bounty!!!

#StackBounty: #solidity #evm #assembly Disassemble "delete array" in solidity

Bounty: 100

am trying to learn about EVM bytes code, but faced this problem.
First, this is the solidity code

pragma solidity ^0.8.0;

contract Assembly {
    function f() public {
        uint8[3] memory a = [1, 2, 3];
        delete a;
    }
}

I just want to know what’ happened under the hood. and for the array init parts, I can understand it.
What I can’t understand is delete a part in bytes code.

I first think delete will make array a‘s elements to the default value, which is zero, but it looks like this.

// maybe delete a?
    005D    5B  JUMPDEST
    005E    60  PUSH1 0x40
    0060    51  MLOAD
    0061    80  DUP1
    0062    60  PUSH1 0x60
    0064    01  ADD
    0065    60  PUSH1 0x40
    0067    52  MSTORE
    0068    80  DUP1
    0069    60  PUSH1 0x03
    006B    90  SWAP1
    006C    60  PUSH1 0x20
    006E    82  DUP3
    006F    02  MUL
    0070    80  DUP1
    0071    36  CALLDATASIZE
    0072    83  DUP4
    0073    37  CALLDATACOPY
    0074    50  POP
    0075    91  SWAP2
    0076    92  SWAP3
    0077    91  SWAP2
    0078    50  POP
    0079    50  POP
    007A    56  *JUMP

Like the solidity code above, I don’t have any calldata in function f. What is this code doing? Why did it call CALLDATASIZE and CALLDATACOPY? And why it makes memory[0x40: 0x40 + 0x20] += 0x60, not just leaving it?

Here is the whole bytes code.

6080604052348015600f57600080fd5b506004361060285760003560e01c806326121ff014602d575b600080fd5b60336035565b005b6040805160608101825260018152600260208201526003918101919091526059605d565b5050565b6040518060600160405280600390602082028036833750919291505056fea264697066735822122054404abffe5e82bae9d564c6e7f48ba27772cdcba99b2066167c1c197e1c063964736f6c63430008040033

Thanks in advance!


Get this bounty!!!

#StackBounty: #solidity #contract-development #chainlink #randomness Including Chainlinks Verifiable Random Function in a "ask squ…

Bounty: 100

After building a Solidity contract that asks another Solidity contract to compute the square root of an Integer (100 in this case), I was wondering: How can I include a query to Chainlinks Verified Random Function to make the contract ask for the root of a random Integer (instead of 100)?

Solidity Contracts

To make the AskRoot contract testable, I’ve adopted a Waffle example called AmIRichYet.sol to also support the askRoot functionality. Its content is:

pragma solidity ^0.6.2;

interface IERC20 {
    function balanceOf(address account) external view returns (uint256);
}

contract AmIRichAlready {
    // define original variables
    IERC20 private tokenContract;
    uint public richness = 1000000 * 10 ** 18;

    // define askroot variables
    bool solved;    // Boolean to denote if contract is solved.
    address payable owner;  // Owner of the contract, first this is the sponser.
    uint expiry;        // Get the time when the contract expires.

    constructor (IERC20 _tokenContract) public {
        tokenContract = _tokenContract;
        
        // specify ask root constructor variables
        solved = false;         //  Boolean value to indicate if contract is already solved.
        owner = msg.sender;     //  Set the owner of the contract to the creator of the contract.
        expiry = 1612569800;    //  Unix timestamp of the moment of expiry.
    }

    function check() public view returns (bool) {
        uint balance = tokenContract.balanceOf(msg.sender);
        return balance > richness;
    }

    // IS THIS NEEDED???: NO
    function setRichness(uint256 _richness) public {
      richness = _richness;
    }
    
    
    // Include askroot functions
    //function test(address payable hunter) public payable {
    function differentFunctionName(address payable hunter) public payable {
        TemplateSolveContract solver = TemplateSolveContract(msg.sender); // The message sender is the contract activating the test function.
        uint x = 100;                                   // Sample input.
        uint16 y = 10;                                  // Sample expected output.
        require(y == solver.main(x), "Wrong output");   // Require the output of the main function to be y.
        solved = true;                                  // Set solved to true.
        owner = hunter;                                 // Set the ownership to the hunter.
        owner.transfer(address(this).balance);          // Transfer the bounty to the hunter.
    }

    // Getter function for the solved variable.
    function getSolved() public view returns (bool){   
        return solved;
    }
    
    // Getter function for the Ownership.
    function getOwner() public view returns (address) { 
        return owner;
    }
    
    // Getter function for the balance of the contract.
    function getBalance() public view returns (uint) {
        return address(this).balance;
    }
    
    // Refund method to claim the value of the contract after expiry.
    function refund() public {
        require(msg.sender == owner && block.timestamp >= expiry, "Contract is not expired yet");   // The sender must own the contract and the contract must be expired.
        selfdestruct(owner);    // Let the contract selfdestruct and move the value to the owner.
    }
}

// TemplateSolveContract so the TestContract knows the structure of the SolveContract.
abstract contract TemplateSolveContract {
    function main(uint x) public virtual returns (uint);
}

Additionally, I integrated a Chainlink VRF contract that is intended to return a random number, with content:

pragma solidity 0.6.2;

import "../chainlink/contracts/src/v0.6/VRFConsumerBase.sol";

contract RandomNumberConsumer is VRFConsumerBase {
    
    bool forTestingPurposes;    // Boolean to run test on this contract
    
    bytes32 internal keyHash;
    uint256 internal fee;
    
    uint256 public randomResult;
    
    /**
     * Constructor inherits VRFConsumerBase
     * 
     * Network: Kovan
     * Chainlink VRF Coordinator address: 0xdD3782915140c8f3b190B5D67eAc6dc5760C46E9
     * LINK token address:                0xa36085F69e2889c224210F603D836748e7dC0088
     * Key Hash: 0x6c3699283bda56ad74f6b855546325b68d482e983852a7a82979cc4807b641f4
     */
    constructor() 
        VRFConsumerBase(
            0xdD3782915140c8f3b190B5D67eAc6dc5760C46E9, // VRF Coordinator
            0xa36085F69e2889c224210F603D836748e7dC0088  // LINK Token
        ) public
    {
        keyHash = 0x6c3699283bda56ad74f6b855546325b68d482e983852a7a82979cc4807b641f4;
        fee = 0.1 * 10 ** 18; // 0.1 LINK
    }
    
    /** 
     * Requests randomness from a user-provided seed
     */
function getRandomNumber() public returns (bytes32 requestId) {
        require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK - fill contract with faucet");
        return requestRandomness(keyHash, fee);
    }

    /**
     * Callback function used by VRF Coordinator
     */
    function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override {
        randomResult = randomness;
    }
    
    // Getter function for the forTestingPurposes boolean.
    function getForTestingPurposes() public view returns (bool){   
        return forTestingPurposes;
    }
}

Testing

And I can test the trival functions (e.g. getters and setters) fine. However when I test getRandomNumber() with:

// custom test in vrfContract
  it('Tests if a random number is returned', async () => {
    expect(await vrfContract.getRandomNumber()).to.be.equal(7);
  });

I do not get an error saying "the random number is not 7", instead, it returns:

Tests if a random number is returned:
     Error: cannot estimate gas; transaction may fail or may require manual gas limit (error={"name":"RuntimeError","results":{"0x0a0b028de6cf6e8446853a300061305501136cefa5f5eb3e96afd95dbd73dd92":{"error":"revert","program_counter":609,"return":"0x"}},"hashes":["0x0a0b028de6cf6e8446853a300061305501136cefa5f5eb3e96afd95dbd73dd92"],"message":"VM Exception while processing transaction: revert"}, tx={"data":"0xdbdff2c1","to":{},"from":"0x17ec8597ff92C3F44523bDc65BF0f1bE632917ff","gasPrice":{"type":"BigNumber","hex":"0x77359400"},"type":0,"nonce":{},"gasLimit":{},"chainId":{}}, code=UNPREDICTABLE_GAS_LIMIT, version=abstract-signer/5.4.1)
      at Logger.makeError (node_modules/@ethersproject/logger/src.ts/index.ts:225:28)
      at Logger.throwError (node_modules/@ethersproject/logger/src.ts/index.ts:237:20)
      at /home/name/git/trucol/tested/new_test/test_vrf3/node_modules/@ethersproject/abstract-signer/src.ts/index.ts:301:31
      at process._tickCallback (internal/process/next_tick.js:68:7)

From watching these instructions: https://docs.chain.link/docs/deploy-your-first-contract/ It seems that I did not fund the contracts with the right test tokens (I assume Ethereum from Ropsten Test Network, and Link from Kovan Test Network), however I do not exactly know which contract has which address yet.
So testing a function in the AmIRichYet.sol contract that calls getRandomNumber() is not yet practical.


Get this bounty!!!

#StackBounty: #solidity #web3js how to detect errors

Bounty: 50

for(var i = 0 ; i <= 4 ; i++){
myContract.methods.contractmanager(i).call().then((res)=>{
console.log(res[0]);
}):
}

there is 2 data stored in my contract and i want to print it but it is not always 2 and it will be more and dynamic and i wont know how many they will be.
after executing this code i have 2 output and 2 error. how to make the loop stop at 2 and it wont show the errors?
how to detect the error and break the loop?
how to find out if the output is empty or not?


Get this bounty!!!

#StackBounty: #solidity #go-ethereum #contract-development #contract-invocation #opcode does using external over public in a library re…

Bounty: 100

I have a library

utils.sol

library Utils {
   struct UtilType {
      unit var1;
      bool var2;
   }

  function addExtra(UtilType storage state, uint extra) public {
    state.var1 += extra;
  }
}

notice the public visibility on addExtra function in utils.sol library.
and that function is being used as follows:

mycontract.sol

import "utils.sol"
contract MyContract {
   using Utils for UtilsType;
   UtilsType state;

  function foo(uint extra) public {
    state.addExtra(extra);
  }
}
  1. will changing public to external in myutils.sol reduce external function call overhead and save any gas?
  2. if so, does the gas savings only occur due to uint variable and not struct type since it’s a storage memory?


Get this bounty!!!