How to call a members function in a Truffle test? - ethereum

Consider the following setting:
contract A {
B public b = new B();
}
contract B {
function C() public pure returns (uint c)
{
c = 5;
}
}
From a Truffle test, having an instance of A, how to call function C?

Here is an example on how to call C in a Truffle test:
const A = artifacts.require('A')
const B = artifacts.require('B')
contract('A', function(accounts) {
it('should be possible to call C', async function() {
let a = await A.new({from: accounts[0]})
let addressOfB = await a.b();
let contractB = web3.eth.contract(B.abi)
let b = contractB.at(addressOfB)
console.log("Output of C: " + await (b.C()).toNumber());
})
})
Contract: A
Output of C: 5
✓ should be possible to call C (380ms)
1 passing (400ms)

Related

Hardhat, ether.js. TypeError: deployer.sendTransaction is not a function error. Trying to execute exactInput UniswapV3 function

Im trying to execute a swap to buy Uni using UniswapV3 interface.
It sends me this error related to the sendTransaction() function and I dont understand why as a lot of examples that I have seen use it this way.
Im using hardhat as you can see and calling the getToken() from another script and deploying on goerli network. Function to check UNI wallet balnceOf() at the end works fine.
Also what advice would you recommend me to improve my code?
This is the code:
const { ethers, getNamedAccounts, network } = require("hardhat")
const {abi: V3SwapRouterABI} = require('#uniswap/v3-periphery/artifacts/contracts/interfaces/ISwapRouter.sol/ISwapRouter.json')
const FEE_SIZE = 3
function encodePath(path, fees) {
if (path.length != fees.length + 1) {
throw new Error('path/fee lengths do not match')
}
let encoded = '0x'
for (let i = 0; i < fees.length; i++) {
// 20 byte encoding of the address
encoded += path[i].slice(2)
// 3 byte encoding of the fee
encoded += fees[i].toString(16).padStart(2 * FEE_SIZE, '0')
}
// encode the final token
encoded += path[path.length - 1].slice(2)
return encoded.toLowerCase()
}
async function getToken() {
// const signer = provider.getSigner()
const deadline = Math.floor(Date.now()/1000) + (60*10)
const wethToken= "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"
const Uni= "0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984"
const UniswapRouter="0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45"
const path = encodePath([wethToken, Uni], [3000])
console.log(path)
const { deployer } = await getNamedAccounts()
const UniV3Contract = await ethers.getContractAt(
V3SwapRouterABI,
UniswapRouter,
deployer
)
const params = {
path: path,
recipient:deployer,
deadline: deadline,
amountIn: ethers.utils.parseEther('0.01'),
amountOutMinimum: 0
}
const encodedData = UniV3Contract.interface.encodeFunctionData("exactInput", [params])
const txArg = {
to: UniswapRouter,
from: deployer,
data: encodedData,
gasLimit: ethers.utils.hexlify(1000000)
}
const tx = await deployer.sendTransaction(txArg)
console.log('tx: ', tx)
const IUni = await ethers.getContractAt(
"IERC20",
Uni,
deployer
)
const UniBlance = await IUni.balanceOf(deployer)
console.log(`Got ${UniBlance.toString()} UNI`)
}
module.exports = { getToken }
Without using the hardhat enviorment:
const {abi: V3SwapRouterABI} = require('#uniswap/v3-periphery/artifacts/contracts/interfaces/ISwapRouter.sol/ISwapRouter.json')
const { ethers } = require("ethers")
require("dotenv").config()
const INFURA_URL_TESTNET = process.env.INFURA_URL_TESTNET
const PRIVATE_KEY = process.env.PRIVATE_KEY
const WALLET_ADDRESS = process.env.WALLET_ADDRESS
// now you can call sendTransaction
const wethToken= "0xB4FBF271143F4FBf7B91A5ded31805e42b2208d6"
const Uni= "0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984"
const UniswapRouter="0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45"
const UniV3Contract = new ethers.Contract(
UniswapRouter,
V3SwapRouterABI
)
const provider = new ethers.providers.JsonRpcProvider(INFURA_URL_TESTNET)
const wallet = new ethers.Wallet(PRIVATE_KEY)
const signer = wallet.connect(provider)
const FEE_SIZE = 3
function encodePath(path, fees) {
if (path.length != fees.length + 1) {
throw new Error('path/fee lengths do not match')
}
let encoded = '0x'
for (let i = 0; i < fees.length; i++) {
// 20 byte encoding of the address
encoded += path[i].slice(2)
// 3 byte encoding of the fee
encoded += fees[i].toString(16).padStart(2 * FEE_SIZE, '0')
}
// encode the final token
encoded += path[path.length - 1].slice(2)
return encoded.toLowerCase()
}
async function getToken() {
const path = encodePath([wethToken, Uni], [3000])
const deadline = Math.floor(Date.now()/1000) + (60*10)
const params = {
path: path,
recipient: WALLET_ADDRESS,
deadline: deadline,
amountIn: ethers.utils.parseEther('0.01'),
amountOutMinimum: 0
}
const encodedData = UniV3Contract.interface.encodeFunctionData("exactInput", [params])
const txArg = {
to: UniswapRouter,
from: WALLET_ADDRESS,
data: encodedData,
gasLimit: ethers.utils.hexlify(1000000)
}
const tx = await signer.sendTransaction(txArg)
console.log('tx: ', tx)
const receipt = tx.wait()
console.log('receipt: ', receipt)
}
module.exports = { getToken }
I could not find documentation for getNamedAccounts but when I check the source code, I get this signature
getNamedAccounts: () => Promise<{
[name: string]: Address;
}>;
this just returns an array of account addresses and used in hardhat.config.js
namedAccounts: {
deployer: {
default: 0, // by default take the first account as deployer
1: 0,
},
},
to send the transaction programmatically:
const { ethers } = require("ethers");
const provider = new ethers.providers.JsonRpcProvider(INFURA_TEST_URL);
const wallet = new ethers.Wallet(WALLET_SECRET);
const signer = wallet.connect(provider);
// now you can call sendTransaction
const tx = await signer.sendTransaction(txArg);

Unable to initialize OpenZeppelin Clone contract during Hardhat Test (Error: VM Exception)

I'm trying to create clones of my implementation contract (EIP-1167) using the OpenZeppelin Clones library, however I keep getting a VM Exception Error.
This is the 'Initialize' function of my Implementation contract:
contract Whoopy is Initializable, VRFConsumerBaseV2, KeeperCompatible {
function initialize(address _whoopyCreator) public initializer {
VRFConsumerBaseV2.initialise(vrfCoordinatorV2);
i_vrfCoordinator = VRFCoordinatorV2Interface(vrfCoordinatorV2);
s_raffleState = RaffleState.CLOSED;
s_lastTimeStamp = block.timestamp;
whoopyCreator = _whoopyCreator;
i_vrfCoordinator.addConsumer(subscriptionId, address(this));
emit NewConsumerAdded(address(this));
}
This is my CloneFactory:
pragma solidity ^0.8.8;
import "#openzeppelin/contracts/proxy/Clones.sol";
contract WhoopyFactory {
address public implementationContract;
address[] public allClones;
event NewClone(address indexed _instance);
mapping(address => address) public whoopyList;
constructor(address _implementation) {
implementationContract = _implementation;
}
function createClone(address _whoopyCreator) payable external returns (address instance) {
instance = Clones.clone(implementationContract);
(bool success, ) = instance.call{value: msg.value}(abi.encodeWithSignature("initialize(address)", _whoopyCreator));
require(success==true, "initialize did not return true");
allClones.push(instance);
whoopyList[_whoopyCreator] = instance;
emit NewClone(instance);
return instance;
}
This is the test I am running:
const { assert, expect } = require("chai")
const { ethers, upgrades } = require("hardhat")
const { networkConfig } = require("../../helper-hardhat-config")
const fs = require("fs")
const path = require("path")
const { web3, Contract } = require("web3")
const getGas = async (tx) => {
const receipt = await ethers.provider.getTransactionReceipt(tx.hash)
return receipt.gasUsed.toString()
}
let whoopy,
Whoopy,
WhoopyFactory,
wf,
whoopyStandaloneGas,
whoopyFactoryGas,
clonedContract,
accountConnectedClone,
wCreator,
wallet,
addr1,
addr2
describe("Whoopy + WhoopyFactory", function () {
it("Initialises contract correctly", async function () {
provider = ethers.provider
addr1 = new ethers.Wallet("0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80", provider)
addr2 = new ethers.Wallet("0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d", provider)
Whoopy = await ethers.getContractFactory("Whoopy", addr1)
whoopy = await Whoopy.deploy()
await whoopy.deployed()
const dir = path.resolve(
__dirname,
"/Users/boss/hardhat-smartcontract-lottery/artifacts/contracts/Whoopy.sol/Whoopy.json"
)
const file = fs.readFileSync(dir, "utf8")
const json = JSON.parse(file)
const abi = json.abi
WhoopyFactory = await ethers.getContractFactory("WhoopyFactory", addr1)
wf = await WhoopyFactory.deploy(whoopy.address)
await wf.deployed()
wf.connect(addr2)
const tx = await wf.createClone("0x70997970C51812dc3A010C7d01b50e0d17dc79C8", {
value: ethers.utils.parseUnits("1", "ether"),
})
console.log(tx)
const txReceipt = await tx.wait(1)
console.log(txReceipt)
})
})
When I run this test, I get the following error:
Error: VM Exception while processing transaction: reverted with reason string 'initialize did not return true'
This exact same code works perfectly when I try it in Remix, so I assume the issue has something to do with Hardhat.
Does anyone have any idea where the issue is? I've been racking my head for days but can't seem to figure out. I'd be extremely grateful if someone can point me in the right direction.
Thanks!
NOTE: Here is my hardhat config (in case it makes a difference):
require("#nomiclabs/hardhat-waffle")
require("#nomiclabs/hardhat-etherscan")
require("hardhat-deploy")
require("solidity-coverage")
require("hardhat-gas-reporter")
require("hardhat-contract-sizer")
require("dotenv").config()
require("#nomiclabs/hardhat-ethers");
// require('#openzeppelin/contracts');
const RINKEBY_RPC_URL = process.env.RINKEBY_RPC_URL
const PRIVATE_KEY = process.env.PRIVATE_KEY
const COINMARKETCAP_API_KEY = process.env.COINMARKETCAP_API_KEY
const ETHERSCAN_API_KEY = process.env.ETHERSCAN_API_KEY
/** #type import('hardhat/config').HardhatUserConfig */
module.exports = {
defaultNetwork: "hardhat",
networks: {
hardhat: {
chainId: 31337,
blockConfirmations: 1
},
localhost: {
chainId: 31337,
},
rinkeby: {
chainId: 4,
blockConfirmations: 6,
url: RINKEBY_RPC_URL,
accounts: [PRIVATE_KEY]
}
},
solidity: "0.8.8",
gasReporter: {
enabled: true,
currency: "USD",
outputFile: "gas-report.txt",
noColors: true,
// coinmarketcap: process.env.COINMARKETCAP_API_KEY,
},
namedAccounts: {
deployer: {
default: 0,
},
player: {
default: 1,
}
},
mocha: {
timeout: 900000,
},
etherscan: {
apiKey: {
rinkeby: ETHERSCAN_API_KEY,
// kovan: ETHERSCAN_API_KEY,
// polygon: POLYGONSCAN_API_KEY,
},
},
};

Ethereum transaction giving error 'invalid sender'

This is how my contract looks like -
pragma solidity >=0.4.25 <0.8.0;
contract Calculator {
uint public result;
event Added(address caller, uint a, uint b, uint res);
constructor() public {
result = 777;
}
function add(uint a, uint b) public returns (uint, address) {
result = a + b;
emit Added(msg.sender, a, b, result);
return (result, msg.sender);
}
}
Above contract is deployed on Ropsten test net. And I am trying to invoke the add(...) function with a transaction. And my code looks like this -
const accountAddress = rtUtil.getAccountAddress();
const accountPk = Buffer.from(rtUtil.getAccountAddressPk(), "hex");
const contract = await rtUtil.getCalculatorContract();
const data = contract.methods.add(3, 74).encodeABI();
const web3 = rtUtil.getWeb3();
const taxCount = await web3.eth.getTransactionCount(accountAddress);
const txObject = {
nonce: web3.utils.toHex(taxCount),
to: rtUtil.getCalculatorContractAddress(),
value: web3.utils.toHex(web3.utils.toWei('0', 'ether')),
gasLimit: web3.utils.toHex(2100000),
gasPrice: web3.utils.toHex(web3.utils.toWei('6', 'gwei')),
data: data
};
const commmon = new Common({chain: "ropsten", hardfork: "petersburg"});
const tx = Transaction.fromTxData(txObject, {commmon});
tx.sign(accountPk);
const serializedTx = tx.serialize();
const raw = web3.utils.toHex(serializedTx);
const transaction = await web3.eth.sendSignedTransaction(raw);
And when I run the code I get error -
Uncaught Error: Returned error: invalid sender
Process exited with code 1
My Nodejs versions is v15.1.0
And my package.json dependencies are -
"dependencies": {
"#ethereumjs/common": "^2.0.0",
"#ethereumjs/tx": "^3.0.0",
"#truffle/contract": "^4.2.30",
"#truffle/hdwallet-provider": "^1.2.0",
"web3": "^1.3.0"
}
Can anyone tell me what I am doing wrong?
Thanks in advance.
In your txObject, you need to specific the chain id.
Add Ropsten's chain id, 3 into txObject.
const txObject = {
nonce: web3.utils.toHex(taxCount),
to: rtUtil.getCalculatorContractAddress(),
value: web3.utils.toHex(web3.utils.toWei('0', 'ether')),
gasLimit: web3.utils.toHex(2100000),
gasPrice: web3.utils.toHex(web3.utils.toWei('6', 'gwei')),
data: data,
chainId: web3.utils.toHex(3)
};
You need to include from in your txObject:
const txObject = {
from: accountAddress,
nonce: web3.utils.toHex(taxCount),
to: rtUtil.getCalculatorContractAddress(),
value: web3.utils.toHex(web3.utils.toWei('0', 'ether')),
gasLimit: web3.utils.toHex(2100000),
gasPrice: web3.utils.toHex(web3.utils.toWei('6', 'gwei')),
data: data
};

Why does the value of a mapping(bytes32 => uint8) seem to change between transaction calls?

The contract code:
pragma solidity ^0.4.10;
contract Test {
mapping (bytes32 => uint8) private dict;
function Test() {}
function Set(bytes32 key, uint8 val) returns (uint8) {
dict[key] = val;
return dict[key];
}
function Get(bytes32 key) returns (uint8) {
return dict[key];
}
}
and I run on testrpc:
contract_file = 'test/test.sol'
contract_name = ':Test'
Solc = require('solc')
Web3 = require('web3')
web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
source_code = fs.readFileSync(contract_file).toString()
compiledContract = Solc.compile(source_code)
abi = compiledContract.contracts[contract_name].interface
bytecode = compiledContract.contracts[contract_name].bytecode;
ContractClass = web3.eth.contract(JSON.parse(abi))
contract_init_data = {
data: bytecode,
from: web3.eth.accounts[0],
gas: 1000000,
}
deployed_contract = ContractClass.new(contract_init_data)
deployed_contract.Set.call("akey", 5)
deployed_contract.Get.call("akey")
bizarrely, this is the output I get in the node terminal:
> deployed_contract.Set.call("akey", 5)
{ [String: '5'] s: 1, e: 0, c: [ 5 ] }
> deployed_contract.Get.call("akey")
{ [String: '0'] s: 1, e: 0, c: [ 0 ] }
This result is the outcome of a long debugging session... what is going on? It seems distinctly like something is broken here, but I followed a tutorial which did something very similar which seems to work...
also:
> Solc.version()
'0.4.11+commit.68ef5810.Emscripten.clang'
Try this deployed_contract.Set("akey", 5) without .call
Because .call on your setter method
executes a message call transaction, which is directly executed in the
VM of the node, but never mined into the blockchain.
doc
The value of the map does not change. I bet 0 is the default value when nothing is set
By the way try using the online compiler you will quickly see if the problem is on the contract or the way you interact with it with web3.

Using Sinon and Chai with ES6 constructor

I'm trying to create unit tests for my class which follows:
MyService.js:
const ApiServce = require('./api-service')
const Config = require('./config')
const Redis = require('ioredis')
class MyService {
constructor () {
const self = this
self.apiService = new ApiServce('MyService', '1.0.0', Config.port)
self.registerRoutes() //this invokes self.apiSerivce.registerRoutes
self.redis = new Redis(Config.redisport, Config.redishost)
self.queueKey = Config.redisqueuekey
}
run () {
const self = this
self.apiService.run()
}
}
module.exports = MyService
Config.js
module.exports = {
port: process.env.SVC_PORT || 8070,
redishost: process.env.REDIS_HOST || '127.0.0.1',
redisport: process.env.REDIS_PORT || 6379,
redisqueuekey: process.env.REDIS_Q_KEY || 'myeventqueue'
}
Test file:
const Redis = require('ioredis')
const MyService = require('../src/myservice')
const ApiService = require('../src/api-service')
const Chai = require('chai')
const Sinon = require('sinon')
const SinonChai = require('sinon-chai')
Chai.use(SinonChai)
const should = Chai.should()
const expect = Chai.expect
describe('MyService', function () {
let apiservicestub, redisstub, apiconststub
beforeEach(function () {
apiservicestub = Sinon.stub(ApiService.prototype, 'registerRoutes')
redisstub = Sinon.stub(Redis.prototype, 'connect')
redisstub.returns(Promise.resolve())
})
describe('.constructor', function () {
it('creates instances of api service and redis client with correct parameters', Sinon.test(function () {
try {
const service = new MyService()
expect(apiservicestub).called
expect(redisstub).called
} catch (e) {
console.error(e)
expect(false)
}
}))
Questions, Issues:
I actually want(ed) to test that the constructors of the dependent classes (apiservice and redis) are being called with the right parameters. But I couldn't find a way so I am currently resorting to one of their methods which is not what I want.
Is there a way in Sinon to achieve this? Do I need to restructure the code to fit Sinon's requirements?
I also want to provide test values for Config items e.g. port to see if they get used. Again I couldn't find a way in Sinon to do that.
I tried the createStubInstance for both 1 and 2 as well but keep getting errors.
Any advice will be appreciated.
In order to make CommonJS modules testable without additional measures, classes should be exclusively used as properties of exports object all through the application. The classes should be destructured from module object in-place. This is not very convenient, but it works with Sinon alone.
I.e.
class ApiService {...}
exports.ApiService = ApiService;
...
const apiServiceModule = require('./api-service');
class MyService {
constructor () {
const { ApiService } = apiServiceModule;
...
In this case the properties on module objects can be mocked before MyService instantiation. Sinon spies don't support classes properly, the constructors should be wrapped:
sinon.stub(apiServiceModule, 'ApiService', function MockedApiService(...) {
return new class { constructor (...) ... };
})
Alternatively, DI can be used, and the app should be refactored according to that. Existing DI libraries (injection-js, inversify, pioc) can handle this job reasonably, but a simple DI pattern looks like this:
class MyService {
constructor (ApiService, ...) {
...
In this case all dependencies can be supplied on construction - both in application and in tests.
But most simple way is to use test-oriented packages that mess with module cache and allow to take control over require calls (rewire, proxyquire, mock-require).
Updated test file, thanks #estus for the direction:
const Redis = require('ioredis')
const ApiService = require('../src/api-service')
const Chai = require('chai')
const Sinon = require('sinon')
const SinonChai = require('sinon-chai')
const Proxyquire = require('proxyquire')
const MyService = require('../src/myservice')
Chai.use(SinonChai)
const should = Chai.should()
const expect = Chai.expect
var namespace = {
apiServiceStubClass: function () {
},
redisStubClass: function () {
}
}
describe('MyService', function () {
let ProxiedMyService
let apiservicestub, redisstub, regroutestub, configstub, apiserviceregroutes, ioredisstub
beforeEach(function () {
apiservicestub = Sinon.stub(namespace, 'apiServiceStubClass')
redisstub = Sinon.stub(namespace, 'redisStubClass')
configstub = {
version: 'testversion',
port: 9999,
redishost: 'testhost',
redisport: 9999,
redisrteventqueuekey: 'testqueyekey'
}
ProxiedMyService = Proxyquire('../src/myservice', {
'./api-service': apiservicestub,
'./config': configstub,
'ioredis': redisstub
})
regroutestub = Sinon.stub(ProxiedMyService.prototype, 'registerRoutes')
regroutestub.returns(true)
apiserviceregroutes = Sinon.stub(ApiService.prototype, 'registerRoutes')
regroutestub.returns(true)
ioredisstub = Sinon.stub(Redis.prototype, 'connect')
ioredisstub.returns(Promise.resolve())
})
afterEach(function () {
namespace.apiServiceStubClass.restore()
namespace.redisStubClass.restore()
ProxiedMyService.prototype.registerRoutes.restore()
ApiService.prototype.registerRoutes.restore()
Redis.prototype.connect.restore()
})
describe('.constructor', function () {
it('creates instances of api service and redis client with correct parameters', Sinon.test(function () {
const service = new ProxiedMyService()
expect(apiservicestub).to.have.been.calledWithNew
expect(apiservicestub).to.have.been.calledWith('MyService', 'testversion', 9999)
expect(regroutestub).to.have.been.called
expect(redisstub).to.have.been.calledWithNew
expect(redisstub).to.have.been.calledWith(9999, 'testhost')
expect(service.queueKey).to.be.equal('testqueyekey')
}))
it('creates redis client using host only when port is -1', Sinon.test(function () {
configstub.redisport = -1
const service = new ProxiedMyService()
expect(redisstub).to.have.been.calledWith('testhost')
}))
})
describe('.registerRoutes', function () {
it('calls apiService registerRoutes with correct url and handler', Sinon.test(function () {
const service = new MyService()
expect.....
}))
})