Reference error- is not defined trying to deploy smart contract - deployment

I'm trying to deploy a smart contract in form of ERC token on truffle local blockchain and it brings up an error, I don't know why.
The code of deploy using java script (test file):
const Dodgi = artifacts.require("Dodgi")
contract("Dodgi", (accounts) => {
before(async () => {
Dodgi = await Dodgi.deployed()
})
is("gives the owner 1 mil tokens", async () => {
let balance = await Dodgi.balanceOf(accounts[0])
})
})
smart contract code:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "#openzeppelin/contracts/token/ERC20/ERC20.sol";
contract Dodgi is ERC20 {
constructor(uint256 _supply) ERC20("Dodgi", "DGL") {
_mint(msg.sender, _supply * (10**decimals()));
}
}

Related

xrpl-accountlib - UnhandledPromiseRejectionWarning: TypeError: AddressCodec.isValidSeed is not a function

Here, I use both isValidAddress and isValidSeed from utils. isValidSeed throws an error, but isValidAddress does not after being used in a similar fashion.
I get no other errors in the code.
if(process.argv.length < 3) {
console.log("Usage: node dist/index <r-address>")
process.exit(1)
}
import { XrplClient } from "xrpl-client"
import { derive, utils, XRPL_Account } from "xrpl-accountlib"
const client = new XrplClient("wss://s.altnet.rippletest.net:51233")
const main =async () => {
const data = await client.send({
id: 1,
command: "account_info",
account: process.argv[2]
})
console.log(data)
//checking isValidAddress usage
if(!utils.isValidAddress(data.account_data.Account)) {
console.log("Invalid r-address")
process.exit(1)
}
console.log("Valid r-address")
//checking isValidSeed usage
if(!utils.isValidSeed(process.argv[2])) {
console.log("Invalid Seed")
process.exit(1)
}
}
main()
which version of the xrpl-accountlib library do you use?
There was a fix regarding the isValidSeed method around December 2021:
Make sure to use the latest version of the xrpl-accountlib.

While testing error responses, the test fails with the expected error (React/Jest/ReactQuery/Axios/MSW)

I am trying to test error states of the following MSW rest endpoint:
import { rest } from 'msw'
export const exceptionHandlers = [
rest.post(config.accountApiUrl + '/login', (req, res, ctx) => {
return res(
ctx.status(500),
ctx.json({ data: { message: 'Mock Error Message' } })
)
})
]
This endpoint is called in a custom hook return function thats using React Query's mutateAsync:
const { mutateAsync } = useMutation(AuthApi.login)
const handleLogin = async (props): Promise<void> => {
await mutateAsync(props, {
onSuccess: async () => {
// this block tests fine
}
onError: async () => {
console.log('!!!')
// it reaches this block, '!!!' is logged to the console,
// but the test still fails with `Request failed with status code 500`
}
})
}
return handleLogin
In a test file:
it('handles network errors', async () => {
mswServer.use(...exceptionHandlers)
const user = userEvent.setup()
const screen = render(<LoginForm />)
const submitButton = screen.getByTestId('Login.Submit')
// Complete form
await user.click(submitButton)
})
It doesnt matter what comes after that, the test always fails with
Request failed with status code 500
at createError (node_modules/axios/lib/core/createError.js:16:15)
at settle (node_modules/axios/lib/core/settle.js:17:12)
at XMLHttpRequestOverride.onloadend (node_modules/axios/lib/adapters/xhr.js:54:7)
at XMLHttpRequestOverride.trigger (node_modules/#mswjs/interceptors/src/interceptors/XMLHttpRequest/XMLHttpRequestOverride.ts:176:17)
at node_modules/#mswjs/interceptors/src/interceptors/XMLHttpRequest/XMLHttpRequestOverride.ts:354:16
But its supposed to fail with status 500. That's the whole point. If I change the handler to return another error, ie ctx.status(404), then the test just fails with that error code.
I've tried wrapping the assertion in a try/catch block but the same thing results. I see examples online of people doing (apparently) exactly this and it works fine, so I'm quite confused what's causing this. All other tests that check success states work as expected.
i've had the same problem.
As far as i could understand, the problem is that in test environment there is no handler for the rejected promise.
https://github.com/TanStack/query/issues/4109

My 'deployed' contract still won't show up on Etherscan. Been about 1.5 hours

need help figuring out why my supposedly 'deployed' contract will still not appear in Etherscan.
Overview:
I used hardhat with following code and got back confirmation:
$ npx hardhat run scripts/deployRoboPunksNFT.js --network rinkeby
RoboPunksNFT deployed to: 0xaBDe0c1A9F7589f21818287287885a2Fef32E3f0
Clearly, it confirms as fully deployed but when I check this contract address at Etherscan (Rinkeby)...nothing: https://rinkeby.etherscan.io/address/0xaBDe0c1A9F7589f21818287287885a2Fef32E3f0
The deployment script used:
const hre = require("hardhat");
async function main() {
const RoboPunksNFT = await hre.ethers.getContractFactory("RoboPunksNFT");
const roboPunksNFT = await RoboPunksNFT.deploy();
await roboPunksNFT.deployed();
console.log("RoboPunksNFT deployed to:", roboPunksNFT.address);
}
main()
.then(() => process.exit(0))
.catch((error) => {
console.error(error);
process.exit(1);
});
My hardhat.config.js
require("#nomiclabs/hardhat-waffle");
const dotenv = require("dotenv");
require("#nomiclabs/hardhat-etherscan");
dotenv.config();
task("accounts", "Prints the list of accounts", async (taskArgs, hre) => {
const accounts = await hre.ethers.getSigners();
for (const account of accounts) {
console.log(account.address);
}
});
/**
* #type import('hardhat/config').HardhatUserConfig
*/
module.exports = {
solidity: "0.8.4",
networks: {
rinkeby: {
url: process.env.REACT_APP_RINKEBY_RPC_URL,
accounts: [process.env.REACT_APP_PRIVATE_KEY]
},
},
etherscan: {
apiKey: process.env.REACT_APP_ETHERSCAN_KEY,
}
};
I got so frustrated that I deployed it again (Code above is 2nd attempt/2nd deployed contract. The first deployed contract address was at 0x9F6040234728493121BCB9A1EaFDBa5E494bB3ed.
Please let me know if anyone sees something that I missed. Hopefully there's enuf info I've submitted here to determine...
Thanks very much!
Problem solved. Rinkeby happened to be down for 6 whole hours. But once it came back up, had 2 freshly deployed contracts on Rinkeby ready to go...

axios / jest - unabled to perform a call request (TypeError: Cannot read property 'then' of undefined)

I'm struggling to perform a test with jest concerning an axios api call
here is my API call, that works perfectly within my program
import axios from 'axios';
import crypto from 'crypto';
import { prop } from 'ramda';
const baseUrl = 'http://gateway.marvel.com:80';
const uri = '/v1/public/characters';
const charactersUrl = baseUrl + uri;
const timestamp = [Math.round(+new Date() / 1000)];
const privateApi = 'XXX';
const publicApi = 'XXX';
const concatenatedString = timestamp.concat(privateApi, publicApi).join('');
const hash = crypto.createHash('md5').update(`${concatenatedString}`).digest('hex');
const charactersApi = () =>
axios
.get(charactersUrl, {
params: {
ts: timestamp,
apikey: publicApi,
hash,
},
})
.then(prop('data'));
export default charactersApi;
When I'm trying to test it, that way:
import axiosMock from 'axios';
import charactersApi from '../marvelApi';
jest.mock('axios', () => ({
get: jest.fn(),
}));
describe('tools | marvelApi', () => {
const piece = { name: '3D-MAN' };
axiosMock.get.mockResolvedValueOnce({ data: piece });
it('should get the character', () => {
return charactersApi().then(elem => {
expect(elem.name).toEqual('3D-MAN');
});
});
});
I get the following message from jest
TypeError: Cannot read property 'then' of undefined
16 |
17 | const charactersApi = () =>
> 18 | axios
| ^
19 | .get(charactersUrl, {
20 | params: {
21 | ts: timestamp,
at charactersApi (src/tools/marvelApi.js:18:3)
at Object.<anonymous> (src/tools/tests/marvelApi.test.js:13:12)
What I have tried
A common error is to forget the return statement within the function that contain the request API, in my case it's done correctly (first piece of code -> charactersApi()) source1, source2
I also tried to return a Promise from the mocked Axios as I have seen on another SO ticket
jest.mock('axios', () => ({
get: jest.fn(() => Promise.resolve()),
}));
I think my axios mock is not correct, because the struggle comes from the test while the production version work well
Any thoughts ?
You can spy on the "axios.get" calls and resolve them to a fixed (mocked) value:
/**
* #jest-environment jsdom
*/
const axios = require('axios')
beforeAll(() => {
jest.spyOn(axios, 'get').mockImplementation()
})
afterAll(() => {
jest.restoreAllMocks()
})
it('returns the mocked response', async () => {
axios.get.mockResolvedValue({ data: 'foo' })
const res = await axios.get('https://api.github.com')
expect(res).toEqual({ data: 'foo' })
})
You shouldn't use jest.mock because it mocks a module that your imported code may be using. As far as I know, it doesn't affect the current module's imports (and you import axios as a part of your test).
Recommended solution
I strongly discourage you from spying/mocking axios directly. See my argumentation below.
You're mocking implementation details of axios. In other words, you take the axios.get function and throw it away, alongside any internal logic it may have, and replace it with a hard mock. This means your test no longer uses axios, instead it uses an emptied mocked shell of axios. This makes your test different from your actual code, which, in turn, decreases the confidence such a test gives you.
You're coupling your mocks with a specific request client (axios). Such an approach is not a long-term investment, as you're writing axios-specific mocks. You can't reuse such mocks for requests made by other clients (i.e. window.fetch, Apollo, etc.), because they have their own implementation details (i.e. window.fetch has no .get() to spy on), which only encourages you to write more implementation-specific logic in tests.
You can learn more about the disadvantages of direct mocking of request clients in the Stop mocking fetch article by Kent C. Dodds. It uses window.fetch mocks as an example, but you may replace it with ANY_REQUEST_CLIENT when reading.
I highly recommend using tools like Mock Service Worker (MSW) that will encourage you to write abstracted mocks that don't rely on any request clients (you can use them no matter how your tested code makes a request) and can even be reused across different testing levels (the same mocks for Jest, Storybook, or Cypress).
Here's how your test would look like with MSW:
import { rest } from 'msw'
import { setupServer } from 'msw/node'
import charactersApi from '../marvelApi';
const server = setupServer(
rest.get('http://gateway.marvel.com:80/v1/public/characters', (req, res, ctx) => {
return res(ctx.json({
data: {
name: '3D-MAN'
}
}))
})
)
beforeAll(() => server.listen()
afterAll(() => server.close())
describe('tools | marvelApi', () => {
it('should get the character', () => {
return charactersApi().then(elem => {
expect(elem.name).toEqual('3D-MAN')
})
})
})
Notice how there are no details about how the request is made, only which request to intercept and mock its response.
You can follow a detailed tutorial on how to Get started with MSW. There's also a great video on API mocking and what problems MSW solves.

Creating LSP (Language Server Protocol) for multiple clients using RPC

I am trying to create a custom LSP.
My goal is to create one language server for both monaco editor (on web) and vscode extension.
Currently I use Node/IPC to connect the vscode-extension with the server.
and ws-jsonrpc to connect monaco editor with the server.
quoting from this article Extending a client with the language server protocol
:
There are multiple ways to use JSON-RPC, but you see these two ways in
most implementations:
Communication is done via the standard input / output, i.e., the command line interface
Communication is performed via TCP/IP, i.e., network messages similar to HTTP
I should be able to use JSON-RPC for both communication (internal communication between processes which is the vscode-extesion in my case , and external communication which is monaco-editor in my case)
Here is how I am launching the server for the moment:
For IPC communication:
const languageServer = new LanguageServer(createConnection(ProposedFeatures.all));
languageServer.start();
For WebSocket RPC:
import * as express from "express";
import * as ws from "ws";
import * as rpc from "vscode-ws-jsonrpc";
import * as url from "url";
import * as http from "http";
import * as net from "net";
const app = express();
const server = app.listen(3000);
const wss = new ws.Server({
noServer: true,
perMessageDeflate: false
});
function launch(socket : rpc.IWebSocket ){
const reader = new rpc.WebSocketMessageReader(socket);
const writer = new rpc.WebSocketMessageWriter(socket);
const languageServer = new LanguageServer(createConnection(reader, writer));
languageServer.start();
}
server.on('upgrade', (request: http.IncomingMessage, socket: net.Socket, head: Buffer) => {
const pathname = request.url ? url.parse(request.url).pathname : undefined;
console.log("server on upgrade ", pathname);
if (pathname === '/sampleServer') {
wss.handleUpgrade(request, socket, head, (webSocket: any) => {
const socket: rpc.IWebSocket = {
send: (content: any) => webSocket.send(content, (error: any) => {
if (error) {
throw error;
}
}),
onMessage: (cb: any) => webSocket.on('message', cb),
onError: (cb: any) => webSocket.on('error', cb),
onClose: (cb: any) => webSocket.on('close', cb),
dispose: () => webSocket.close()
};
// launch the server when the web socket is opened
if (webSocket.readyState === webSocket.OPEN) {
launch(socket);
} else {
webSocket.on('open', () => {
launch(socket);
});
}
});
}
})
The server that you are using should not operate with multiple clients using it at the same time. It even says: "the protocol currently assumes that one server serves one tool.". Also, maybe read this article about your topic. **https://code.visualstudio.com/api/language-extensions/language-server-extension-guide **