alchemyplatform / alchemy-web3 Goto Github PK
View Code? Open in Web Editor NEWWeb3 client extended with Alchemy integration
License: MIT License
Web3 client extended with Alchemy integration
License: MIT License
This repo comes in typescript without comments, and without any sort of idea what is going on under the hood. I don't know where to find the unminified build so I can take out all the bloat in Web3 I don't need. The minified file is a whopping 1.4MB. It's far too big for something that just needs basic contract calls, and goes out over mobile.
Details:
Error thrown on line 58 of sendRestPayloaddist/cjs/web3-adapter/sendRestPayload.js seems to bypass outside try catch statements of outside program calling web3.alchemy.getNftMetadata.
Whenever this error occurs and a 500 internal server error comes back from a call, the outside program exists immediately without entering any outside try/catch statements, even if the whole program is wrapped in try catch. Also no luck checking for promise rejections. Could this be because this error is coming from another thread or something?
Full error msg is as follows :
throw new Error(response.status + ":" + response.statusText);
^
Error: 500:Error getting NFT Metadata
at Object.<anonymous> (/home/dak/Desktop/wise/contract_repos/merkle-tree/liquid-pool-merkle-price-tree/generate/node_modules/@alch/alchemy-web3/dist/cjs/web3-adapter/sendRestPayload.js:58:35)
at step (/home/dak/Desktop/wise/contract_repos/merkle-tree/liquid-pool-merkle-price-tree/generate/node_modules/tslib/tslib.js:143:27)
at Object.next (/home/dak/Desktop/wise/contract_repos/merkle-tree/liquid-pool-merkle-price-tree/generate/node_modules/tslib/tslib.js:124:57)
at fulfilled (/home/dak/Desktop/wise/contract_repos/merkle-tree/liquid-pool-merkle-price-tree/generate/node_modules/tslib/tslib.js:114:62)
at runMicrotasks (<anonymous>)
at processTicksAndRejections (node:internal/process/task_queues:96:5)```
Is it possible to use the Notify API of Alchemy Platform with alchemy-web3. Could you please share some examples.
Code
const { alchemy } = createAlchemyWeb3(ALCHEMY_URL);
const test = { contractAddress: "0x6688Ee4E6e17a9cF88A13Da833b011E64C2B4203", tokenId: "1" };
const nft = await alchemy.getNftMetadata(test);
console.dir(nft);
Description of Problem
while fetching an NFT, I am trying to access a few properties inside the metadata
property on the response such as external_url
and animation_url
. I realize that these are not standard necessarily (though common), so I cannot expect to receive these as responses all the time.
This interface is currently described by the following interface:
alchemy-web3/src/alchemy-apis/types.ts
Lines 81 to 86 in 5d3985f
As a user I would expect that these non-standard properties would either be listed as optional types on this interface, or to just be jammed into attributes
record (or else some "optional_properties" record of some sort if the attributes
actually usually holds other more standardized data.
Hi Alchemy,
I have a bug from the "getAllClaimerAddresses" :
here is the line of code:
"const walletAddresses = await editionDrop.history.getAllClaimerAddresses(0);"
===>>> give reason: 'timeout',
code: 'TIMEOUT',
requestBody: '{"method":"eth_getLogs","params":[{"fromBlock":"0x0","toBlock":"0x78b4ce","address":"0x3519b6ccdea895f2606f350f9d90f2cb685a6f57","topics":["0x4f72e6585331094d368e469f11198272039d08cbddfcda1577e192687a83afb6"]}],"id":42,"jsonrpc":"2.0"}',
requestMethod: 'POST',
timeout: 120000,
url: 'https://eth-goerli.alchemyapi.io/v2/_gg7wSSi0KMBsdKnGVfHDueq6xMB9EkC'
just before this error, I got this unjustified warning:
========= NOTICE =========
Request-Rate Exceeded (this message will not be repeated)
The default API keys for each service are provided as a highly-throttled,
community resource for low-traffic projects and early prototyping.
While your application will continue to function, we highly recommended
signing up for your own API keys to improve performance, increase your
request rate/limit and enable other perks, such as metrics and advanced APIs.
For the error above, I tried also the code : "getAllClaimerAddresses" from Thirdweb and I get the same error.
https://portal.thirdweb.com/typescript/sdk.droperc1155history.getallclaimeraddresses
This is unjustified because I have an Alchemy account and an API Key.
Thank you
It fails to filter out the other addresses. For example on Ropsten:
const nfts = await alchemy.getNfts({
owner: "0xc9a6EC4aE16AD5A1B75Cf8f111FBD69eC3788774",
contractAddresses: ["0x18e132bE028b77e6bb9bE98620bB335005077907"],
});
console.log("nfts", nfts);
Response includes addresses other than "0x18e132bE028b77e6bb9bE98620bB335005077907":
On closer inspection of the network tab, the library is sending the following params:
/v1/getNFTs/?owner=0xc9a6EC4aE16AD5A1B75Cf8f111FBD69eC3788774&contractAddresses=0x18e132bE028b77e6bb9bE98620bB335005077907
But this differs from the example in the documentation which says it should be:
/v1/getNFTs/?owner=0xc9a6EC4aE16AD5A1B75Cf8f111FBD69eC3788774&contractAddresses[]=0x18e132bE028b77e6bb9bE98620bB335005077907
(Note the additional []
after contractAddresses).
After using the format in the documentation, I get the expected result:
Hey there, Alchemy team!
Trying to use the new alchemy_fullPendingTransactions
feature (#15), but it doesn't seem to be working. I get the following stack trace when attempting to subscribe to alchemy_fullPendingTransactions
(the correct channel per the docs):
Unknown subscription: alchemy_fullPendingTransactions
at SubscriptionsFactory.getSubscription (web3-eth.umd.js:362)
at SubscriptionsFactory.subscriptionsFactory.getSubscription (index.js:163)
at Proxy.subscribe (web3-eth.umd.js:414)
at useAlchemyRpcWeb3.tsx:25
at commitHookEffectList (react-dom.development.js:22030)
...more unrelated react errors
Below is a snippet of code I'm using, it's a basic React hook that runs in the browser:
import { useEffect, useRef } from 'react'
import { createAlchemyWeb3 } from '@alch/alchemy-web3'
import { HTTP_ALCHEMY } from '../utils/connectors'
const useAlchemyRpcWeb3 = (alchemyUrl = HTTP_ALCHEMY) => {
const alchemyWeb3Ref = useRef(createAlchemyWeb3(alchemyUrl))
useEffect(() => {
alchemyWeb3Ref.current = createAlchemyWeb3(alchemyUrl)
}, [alchemyUrl])
// Test hook just to see subscriptions
useEffect(() => {
if (!alchemyWeb3Ref.current) {
return
}
let sub: any = undefined
try {
sub = alchemyWeb3Ref.current.eth.subscribe(
'alchemy_fullPendingTransactions',
{},
(err, item) => {
if (err) {
console.log('alchemy_fullPendingTransactions:error', err)
return
}
console.log('alchemy_fullPendingTransactions:item', item)
},
)
} catch (e) {
console.log('error setting up alchemy sub', e)
}
return () => {
if (sub) {
sub.unsubscribe()
}
}
}, [alchemyWeb3Ref.current])
return alchemyWeb3Ref.current
}
export { useAlchemyRpcWeb3 }
I've tried both the HTTP and WSS keys, just in case.
Let me know if you need a better repro, or if I'm just doing something wrong.
Thanks!
> node_modules/swarm-js/node_modules/got/index.js:45:28: error: Could not resolve "electron" (mark it as external to exclude it from the bundle, or surround it with try/catch to handle the failure at run-time)
45 β const electron = require('electron');
β΅ ~~~~~~~~~~
=> Found "[email protected]"
info Reasons this module exists
- "web3#web3-bzz" depends on it
- Hoisted from "web3#web3-bzz#swarm-js"
- Hoisted from "@alch#alchemy-web3#web3#web3-bzz#swarm-js"
- Hoisted from "@alch#alchemy-web3#@types#web3#web3#web3-bzz#swarm-js"
info Disk size without dependencies: "1.17MB"
info Disk size with unique dependencies: "3.46MB"
info Disk size with transitive dependencies: "5.87MB"
info Number of shared dependencies: 69
Done in 2.09s.
When I look at package.json I see:
https://github.com/alchemyplatform/alchemy-web3/blob/master/package.json#L67 Shouldn't they be in dev-dependencies?
Node: 14.17.1
Env: netlify serverless function
starter-files
npm install
npm install @alch/alchemy-web3
const { createAlchemyWeb3 } = require("@alch/alchemy-web3");
on the top of starter-files/src/util/interact.js
npm start
Network: Ethereum
API request: getNFTs
Easiest way to replicate: /getNFTs on wallet address 0x2bdeA27111B606551a1D3c19c0e8c73e0081ecBA
One NFT has metadata.image and the other has metadata.image_url
I get that this is not exactly an issue with the typing but more at the API level. Feel free to redirect this issue anywhere that would be best to address it.
Thanks!
Network: Ethereum
API request: getNFTs
Easiest way to replicate: /getNFTs on wallet address 0x2bdeA27111B606551a1D3c19c0e8c73e0081ecBA (I guess that any wallet would do)
The types defined in @alch/alchemy-web3 v1.4.2 are media.uri.gateway and media.uri.raw where as the API returns media.gateway and media.raw
Thanks!
The document https://docs.alchemy.com/alchemy/enhanced-apis/subscription-api-websockets#alchemy_pendingtransactions and typings of this SDK are not consistent in method name and args, I'm not sure which one should I trust.
Im trying to get transaction history for address to work but get this error.
Error: Invalid category param: category must be a non-empty list containing the possible values: {external, internal, token, erc20, erc721, erc1155, specialnft}
code:
async getTransactionsAlchemy(address: string) {
const alchemyWeb3 = createAlchemyWeb3(EthereumConstants.ALCHEMY_GOERLI_PROVIDER_URL);
const transactions = await alchemyWeb3.alchemy.getAssetTransfers({ fromBlock: "0x0", fromAddress: address, });
return transactions;
}
The legacy style of using contracts looks like this:
const account = web3.eth.accounts.privateKeyToAccount(privateKey);
web3.eth.accounts.wallet.add(account);
const from = account.address;
const contract = new web3.eth.Contract(abi, contractAddress, {from: from});
// Call a function that requires gas
contract.methods.updateName("alchemy").send({gas: 12345, gasPrice: currentGasPrice});
If I remove gasPrice it still sends it as a legacy transaction. If I add maxPriorityFeePerGas
then I get this error:
Error: eip-1559 transactions don't support gasPrice
I've tried setting gasPrice to undefined but it doesn't help.
I'm able to get it to work following your tutorial here:
https://docs.alchemy.com/alchemy/tutorials/hello-world-smart-contract/interacting-with-a-smart-contract
But I feel like that tutorial makes the process so much harder. Why should I have to encode and sign each individual transaction, when I can do the same thing in 4 lines of code? That tutorial seems very out dated with what web3 is capable of doing.
I am using version 1.3.0
of the library, and I am trying the following:
web3.eth.getMaxPriorityFeePerGas().then(console.log);
But there is no getMaxPriorityFeePerGas
method defined. Am I doing something wrong?
I'm trying to sign a message and recover it using web3. The wrapper seems to make a network call, which arguably shouldn't happen with ecRecover.
To reproduce, use this code:
var signedData = await web3.eth.personal.sign(msg, walletAddress, "")
const recovered = await web3.eth.personal.ecRecover(msg, signedData)
console.log(recovered)
Oh, and not using the Alchemy Web3 wrapper works perfectly.
I have a project with dependencies as
"devDependencies": {
"@types/bs58": "^4.0.1",
"@types/buffers": "^0.1.31",
"@types/chai": "^4.3.0",
"@types/express": "^4.17.13",
"@types/jest": "^27.4.1",
"@types/jsonwebtoken": "^8.5.8",
"@types/mocha": "^9.1.0",
"@types/nock": "^11.1.0",
"@types/sinon": "^10.0.11",
"@typescript-eslint/eslint-plugin": "^5.17.0",
"@typescript-eslint/parser": "^5.17.0",
"chai": "^4.3.6",
"chai-http": "^4.3.0",
"concurrently": "^7.0.0",
"eslint": "^8.12.0",
"eslint-config-prettier": "^8.5.0",
"eslint-plugin-prettier": "^4.0.0",
"jest": "^27.5.1",
"mocha": "^9.2.2",
"nock": "^13.2.4",
"nodemon": "^2.0.15",
"prettier": "2.6.1",
"sinon": "^13.0.1",
"ts-node": "^10.7.0",
"typescript": "^4.6.3"
},
"dependencies": {
"@alch/alchemy-web3": "^1.4.4",
"@aws-sdk/client-s3": "^3.58.0",
"@bitpack-me/entitybit": "0.0.40",
"@ethereumjs/tx": "^3.5.2",
"@solana/buffer-layout": "^4.0.0",
"@solana/spl-token": "0.1.8",
"@solana/web3.js": "1.39.1",
"@types/cors": "^2.8.12",
"@types/debug": "^4.1.7",
"@types/valid-url": "^1.0.3",
"axios": "^0.27.2",
"base64url": "^3.0.1",
"borsh": "^0.7.0",
"class-validator": "^0.13.2",
"cloudinary": "^1.29.0",
"cors": "^2.8.5",
"crypto": "^1.0.1",
"dotenv": "^16.0.0",
"express": "^4.17.3",
"express-promise-router": "^4.1.1",
"express-validator": "^6.14.0",
"express-winston": "^4.2.0",
"form-data": "^4.0.0",
"fs": "^0.0.1-security",
"js-sha3": "^0.8.0",
"jsonwebtoken": "^8.5.1",
"razorpay": "^2.8.1",
"sturdy-websocket": "^0.2.1",
"twilio": "^3.76.0",
"typeorm": "0.3.1",
"url-join-ts": "^1.0.5",
"valid-url": "^1.0.9",
"web3": "^1.7.1",
"web3-utils": "^1.7.1",
"winston": "^3.6.0",
"ws": "^8.8.0"
},
"peerDependencies": {
"@types/node": "^18.0.0"
},
"optionalDependencies": {
"bufferutil": "^4.0.6",
"utf-8-validate": "^5.0.9"
}
Upon building the project with tsc --project ./
I get the following error.
node_modules/@alch/alchemy-web3/node_modules/@types/bn.js/index.d.ts:8:23 - error TS4090: Conflicting definitions for 'node' found at '/Users/p/workspace/Back/node_modules/@alch/alchemy-web3/node_modules/@types/node/index.d.ts' and '/Users/p/workspace/Back/node_modules/@types/node/index.d.ts'. Consider installing a specific version of this library to resolve the conflict.
The file is in the program because:
Type library referenced via 'node' from file '/Users/p/workspace/Back/node_modules/dotenv/lib/main.d.ts' with packageId '@types/node/[email protected]'
Type library referenced via 'node' from file '/Users/p/workspace/Back/node_modules/@alch/alchemy-web3/node_modules/@types/bn.js/index.d.ts' with packageId '@types/node/[email protected]'
8 /// <reference types="node"/>
~~~~
node_modules/dotenv/lib/main.d.ts:2:23
2 /// <reference types="node" />
~~~~
File is included via type library reference here.
Found 1 error in node_modules/@alch/alchemy-web3/node_modules/@types/bn.js/index.d.ts:8
I understand this may be out of scope for this repo, but any help is appreciated.
I got this error in my editor after trying to get token balance.
The result after calling API look like this.
const balances: TokenBalancesResponse = {
address: <owner_address>,
tokenBalances: [
{
contractAddress: '0xBCa9c16d41BF2b9AE42f96d240015c8B5cb22DB7',
tokenBalance: '7973019999999999999879',
error: null
}
]
}
Then I tried to get tokenBalances[0].contractAddress but the editor alert that this property does not exist.
When I check types.ts in your source below, it shows only property address.
/// from your api [src/alchemy-apis/types.ts]
export interface TokenBalancesResponse {
address: string;
tokenBalances: TokenBalance[];
}
export type TokenBalance = TokenBalanceSuccess | TokenBalanceFailure;
export interface TokenBalanceSuccess {
address: string;
tokenBalance: string;
error: null;
}
from the readme:
web3.eth.getAccounts().then((accounts) => {
web3.eth.sendTransaction({
from: accounts[0],
to: "0x6A823Eβ¦",
value: "1000000000000000000",
});
});
here's my code:
const transactionParameters = {
to: contractAddress,
value: "1000000000000000000",
from: window.ethereum.selectedAddress,
data: window.contract.methods
.createCollectible(window.ethereum.selectedAddress, tokenURI)
.encodeABI(),
};
results in a transaction for 4722.366483
ETH. what's wrong here?
i tried using a different BN library but it results in the same thing.
in src/index.ts we find this:
patchSubscriptions(alchemyWeb3);
patchEnableCustomRPC(alchemyWeb3);
patchEthFeeHistoryMethod(alchemyWeb3);
patchEthMaxPriorityFeePerGasMethod(alchemyWeb3);
Yet unfortunately when using these methods in typescript, no types are found for the patched methods.
Please provide correct types
Node => v17.3.0
NPM => 8.3.0
"react-scripts": "5.0.0",
"@alch/alchemy-web3": "^1.2.4",
sendRestPayload.js:17 Uncaught TypeError: Cannot read properties of undefined (reading 'includes')
at makeRestPayloadSender (sendRestPayload.js:17:1)
at makeAlchemyContext (alchemyContext.js:15:1)
at createAlchemyWeb3 (index.js:20:1)
at Module../src/services/mint.js (mint.js:7:1)
at Module.options.factory (react refresh:6:1)
at webpack_require (bootstrap:24:1)
at fn (hot module replacement:61:1)
at Module../src/components/mint/index.js (marketing.js:98:1)
at Module.options.factory (react refresh:6:1)
at webpack_require (bootstrap:24:1)
Version: 1.2.2
All logs returned should have a topic length of 4 (as specifiec by the query.). The Alchemy composer does this
but AlchemyWeb3.eth.subscribe("logs", topics: [["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"], [], [], []]) does not.
Your docs say valid values for the second parameter are:
One of:
Array - A list of contract addresses
The String"DEFAULT_TOKENS" - denotes a query for the top 100 tokens by 24 hour volume
However, I get
error TS2345: Argument of type 'string' is not assignable to parameter of type 'string[]'.
when I call
const balances = await web3.alchemy.getTokenBalances(
'foo',
'DEFAULT_TOKENS',
);
Im trying to access alchemy web3 with next.js. But it is not able to call createAlchemyWeb3
What could be a possible issue?
Assettransferaspams is missing the declaration withmetadata
Hi, Im using alchemy within a React app but I get the following error:
if (!url.includes("alchemy")) {
^
TypeError: Cannot read properties of undefined (reading 'includes')
at Object.makeRestPayloadSender (C:\Users\alexi\Desktop\NFT-Block-Slimes\node_modules\@alch\alchemy-web3\dist\cjs\web3-adapter\sendRestPayload.js:16:14)
at Object.makeAlchemyContext (C:\Users\alexi\Desktop\NFT-Block-Slimes\node_modules\@alch\alchemy-web3\dist\cjs\web3-adapter\alchemyContext.js:18:40)
at createAlchemyWeb3 (C:\Users\alexi\Desktop\NFT-Block-Slimes\node_modules\@alch\alchemy-web3\dist\cjs\index.js:21:31)
Any help would be appreciated
Hi, I have several errors of the same type when I try to use require("@alch/alchemy-web3")
. I'm following this guide
Errors look like:
Compiled with problems:
ERROR in ./node_modules/cipher-base/index.js 3:16-43
Module not found: Error: Can't resolve 'stream' in '/home/.../node_modules/cipher-base'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "stream": require.resolve("stream-browserify") }'
- install 'stream-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "stream": false }
ERROR in ./node_modules/eth-lib/lib/bytes.js 9:193-227
Module not found: Error: Can't resolve 'crypto' in '/home/.../node_modules/eth-lib/lib'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "crypto": require.resolve("crypto-browserify") }'
- install 'crypto-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "crypto": false }
ERROR in ./node_modules/ethereumjs-util/dist.browser/account.js 39:31-48
Module not found: Error: Can't resolve 'assert' in '/home/.../node_modules/ethereumjs-util/dist.browser'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "assert": require.resolve("assert/") }'
- install 'assert'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "assert": false }
I tried to run the compiled tutorial but got the same errors.
Hello! I burned the token, but for some reason AlchemyAPI returns it anyway.
Network: Polygon Mumbai
API request: getNFTs
{
"ownedNfts": [
{
"contract": {
"address": "0x356881528562ab0f269a5d1982fd21b83fb835b0"
},
"id": {
"tokenId": "86",
"tokenMetadata": {
"tokenType": "ERC721"
}
},
"title": "",
"description": "",
"tokenUri": {
"raw": "Unable to get token URI",
"gateway": ""
},
"media": [
{
"raw": "",
"gateway": ""
}
],
"metadata": {},
"timeLastUpdated": "2022-05-06T10:47:18.835Z",
"error": "Token does not exist"
}
],
"totalCount": 1,
"blockHash": "0xb15dfe1fb416408406ea54946b6339a17b04f1725934e80e6c4137de964ff06e"
}
Hi, I don't know if this is the right place, apologies in any case, I have created a test token in Rinkeby (OpenSea), and I am trying to transfer it without going through the web, but directly through the contract.
I have now the problem with the safeTransferFrom(..) after executing the setApprovalForAll().
The setApprovalForAll() runs fine, and I can see its hash and the transaction check.
Now, with the safeTransferFrom() I get the hash, but when I go to look it up in Rinkeby, it doesn't exist.
I am using Alchemy.
Any suggestions?
thanks
The docs have an option to fetch metadata when fetching nfts. This package doesn't support it:
Docs: https://docs.alchemy.com/alchemy/enhanced-apis/nft-api/getnfts#parameters
withMetadata: (optional) includes metadata for each returned token
Types for this package:
export interface GetNftsParams {
owner: string;
pageKey?: string;
contractAddresses?: string[];
}
Code snippet for web3
creation is as follows:
web3 = createAlchemyWeb3('https://eth-goerli.alchemyapi.io/v2/-Dm....your...key')
Error is thrown from the estimateGas
call as follows:
web3.eth.estimateGas({ data, to, from, value })
Error is:
Node error: {"code":-32000,"message":"invalid opcode: opcode 0xdb not defined"}
at Function.validate (web3-providers.umd.js:112)
at CustomProvider._callee$ (web3-providers.umd.js:1157)
at tryCatch (runtime.js:63)
at Generator.invoke [as _invoke] (runtime.js:293)
at Generator.next (runtime.js:118)
at asyncGeneratorStep (asyncToGenerator.js:3)
at _next (asyncToGenerator.js:25)
Version:
"@alch/alchemy-web3": "^0.1.18"
This kind of error does not happen when using the standard web3
with the same code and environment (browser with Metamask)
I am trying to implement sendTransaction
method in React Native.
I can't connect to crypto wallets.
Should i use a package like walletConnect
?
Do you have an example of this?
Using this inside React (react scripts v4.0.3) I'm getting the following error occuring, not always on page load but somewhat randomly.
VM6639:2 Uncaught ReferenceError: process is not defined
at Object.4043 (<anonymous>:2:13168)
at r (<anonymous>:2:306599)
at Object.8048 (<anonymous>:2:9496)
at r (<anonymous>:2:306599)
at Object.8641 (<anonymous>:2:1379)
at r (<anonymous>:2:306599)
at <anonymous>:2:315627
at <anonymous>:2:324225
at <anonymous>:2:324229
at HTMLIFrameElement.e.onload (index.js:1:1)
I'm unsure exactly what is causing this, but it appears to be from the underlying web3.js
having dependencies from node and hence on process.
Do you have any suggestions? Am I doing something wrong here?
I encounter this error when I try to call to a contract for the browser:
Wrong response id alc-web3:0 (expected: 8) in {"jsonrpc":"2.0","id":8,"method":"eth_sendTransaction","params":[{"value":"0xde0b6b3a7640000","from":"0x308163aea0cae49b4d4014374ae77f8cb6a6142e","to":"0xf1f364b55200b999768ea4329891833576ea4916","gas":"0x15f90","data":"0x8a83fbeb000000000000000000000000000000000000000000000000000000000000029b","gasPrice":"0x3b9aca00"}]}
The transaction is accepted in the MetaMask popup.
const injectedProvider = window.ethereum ?? window.web3?.currentProvider
const w3 = createAlchemyWeb3(
'wss://eth-mainnet.ws.alchemyapi.io/ws/<...>',
injectedProvider ? { writeProvider: injectedProvider } : undefined,
)
w3.eth.handleRevert = true
try {
await web3.eth.sendTransaction({
value: web3.utils.toWei('1', 'ether'),
from: account,
to: contractAddress,
gas: 90000,
data: contract.methods.send().encodeABI(),
})
} catch (err) {
// error can't be caught here
console.error(err)
}
Below is the code snippet for initiating web3
with Alchemy provider
import Web3 from 'web3'
const web3 = new Web3('https://eth-goerli.alchemyapi.io/v2/my-key')
Request
{"jsonrpc":"2.0","id":44,"method":"eth_sendTransaction","params":[{"from":"0xa7fc2009cc8b36997ef533dec396d6b4b00760e4","value":"0x16345785d8a0000","gas":"0x249f0","data":"0x4faa8a26000000000000000000000000a7fc2009cc8b36997ef533dec396d6b4b00760e4","gasPrice":"0x49504f80","to":"0xbbd7cbfa79faee899eaf900f13c9065bf03b1a74"}]}
Response
{"jsonrpc": "2.0", "id": 44, "error": {"code": -32601, "message": "Unsupported method [eth_sendTransaction]. See available methods at https://docs.alchemyapi.io/documentation/alchemy-api-reference/json-rpc"}}
There seems to be some issue with the types exports for @alch/alchemy-web3
v1.1.11.
import {
AssetTransfersCategory,
AssetTransfersParams,
AssetTransfersResult,
} from '@alch/alchemy-web3'
/// Module '"@alch/alchemy-web3"' has no exported member 'AssetTransfersResult'.ts(2305)
I wasn't able to see anything strange in the build or structure of the types file between 1.1.9 (working) and 1.1.11.
We fetch auctions but the smart contract throws an error when the auction doesn't exist.
We don't mind about that and just want to skip the error.
This line works for web3 but shows an Unhandled Promise error when using this library:
return await salesInstance.methods.getAuction(id).call().catch(err => null)
import {pinJSONToIPFS} from './pinata.js'
require('dotenv').config();
const alchemyKey = process.env.ALCHEMY_KEY;
const { createAlchemyWeb3 } = require("@alch/alchemy-web3");
const web3 = createAlchemyWeb3(alchemyKey);
const contractABI = require('../contract-abi.json')
const contractAddress = process.env.CONTRACT_ADDRESS;
export const mintNFTWeb3 = async (url, name, description) => {
//error handling
if (url.trim() == "" || (name.trim() == "" || description.trim() == "")) {
return {
success: false,
status: "βPlease make sure all fields are completed before minting.",
}
}
//make metadata
const metadata = new Object();
metadata.name = name;
metadata.image = url;
metadata.description = description;
//make pinata call
const pinataResponse = await pinJSONToIPFS(metadata);
if (!pinataResponse.success) {
return {
success: false,
status: "π’ Something went wrong while uploading your tokenURI.",
}
}
const tokenURI = pinataResponse.pinataUrl;
// window.contract = await new web3.eth.Contract(contractABI, contractAddress);
//set up your Ethereum transaction
const transactionParameters = {
to: contractAddress, // Required except during contract publications.
from: window.ethereum.selectedAddress, // must match user's active address.
'data': window.contract.methods.mintNFT(window.ethereum.selectedAddress, tokenURI).encodeABI()//make call to NFT smart contract
};
//sign the transaction via Metamask
try {
const txHash = await window.ethereum
.request({
method: 'eth_sendTransaction',
params: [transactionParameters],
});
return {
success: true,
status: "β
Check out your transaction on Etherscan: https://ropsten.etherscan.io/tx/" + txHash
}
} catch (error) {
return {
success: false,
status: "π₯ Something went wrong: " + error.message
}
}
}
Network: Ethereum
API request: getNFTs
Description:
When there is an ENS name (e.g. snowkey.eth
) which was expired but re-registered, the getNFTs
api returns as unknown.name
{
"ownedNfts": [
{
"contract": {
"address": "0x57f1887a8bf19b14fc0df6fd9b2acc9af147ea85"
},
"id": {
"tokenId": "0x1fd4be701083c6c7847de1aa3d7653eecd639442579b7ca2db49bfe050e0cee9",
"tokenMetadata": {
"tokenType": "ERC721"
}
},
"balance": "1",
"title": "",
"description": "",
"tokenUri": {
"raw": "https://metadata.ens.domains/mainnet/0x57f1887a8bf19b14fc0df6fd9b2acc9af147ea85/0x1fd4be701083c6c7847de1aa3d7653eecd639442579b7ca2db49bfe050e0cee9",
"gateway": "https://metadata.ens.domains/mainnet/0x57f1887a8bf19b14fc0df6fd9b2acc9af147ea85/0x1fd4be701083c6c7847de1aa3d7653eecd639442579b7ca2db49bfe050e0cee9"
},
"media": [
{
"raw": "",
"gateway": ""
}
],
"metadata": {
"message": {
"name": "unknown.name",
"description": "Unknown ENS name",
"attributes": [
{
"display_type": "date",
"value": 1580346653000000,
"trait_type": "Created Date"
},
{
"display_type": "number",
"value": 7,
"trait_type": "Length"
},
{
"display_type": "string",
"value": "letter",
"trait_type": "Character Set"
}
],
"name_length": 7,
"version": 0,
"is_normalized": true
}
},
"timeLastUpdated": "2022-05-13T22:44:09.700Z"
},
......
],
"totalCount": 2,
"blockHash": "0xe429b2fe7874b2cefefa1a76c8350bf8709657a3438d8d24df997a4ca807bed2"
}
https://github.com/alchemyplatform/alchemy-web3/blob/master/src/index.ts#L237-L260 incorrectly converts hex values to decimals in some cases.
Please consider using web3-util's version instead, as it is already installed and quite robust.
Given the valid hex value 0x0000000000000000000000000000000000000000000000004563918244f40072
(i.e. 5 DAI) the function will incorrectly convert it to 500
instead of 5000000000000000114
Codesandbox repro along with a proposed fix: https://codesandbox.io/s/infallible-cache-kmomc
web3.eth.subscribe("newBlockHeaders", { }).on("data", async (blockHelper) => { console.log(blockHelper) })
An error has occurred
return new Error('Invalid number of parameters for "' + method + '". Got ' + got + ' expected ' + expected + '!'); Error: Invalid number of parameters for "newHeads". Got 1 expected 0!
When running web3.alchemy.getTransactionReceipts()
, you receive a TransactionReceiptsResponse
, which contains an array of TransactionReceipt
in the receipts
key.
These TransactionReceipt
objects are typed using the web3.js TransactionReceipt
interface, which defines the following:
export interface TransactionReceipt {
status: boolean;
transactionHash: string;
transactionIndex: number;
blockHash: string;
blockNumber: number;
from: string;
to: string;
contractAddress?: string;
cumulativeGasUsed: number;
gasUsed: number;
logs: Log[];
logsBloom: string;
events?: {
[eventName: string]: EventLog;
};
}
Looking at one of the actual elements it returns, there are some differences:
blockHash:"0x1f302b67a0274bce84ba8c051259073adf3861cda348ebe7d503e88341d12dc4"
blockNumber:"0xd89734"
contractAddress:null
cumulativeGasUsed:"0x22eea"
effectiveGasPrice:"0xdabb435e5"
from:"0xb58555fcba6479fced7de1485eb054943a09af7b"
gasUsed:"0x22eea"
logs:Array(3) [Object, Object, Object]
logsBloom:"0x000..."
status:"0x1"
to:"0x00000000003b3cc22af3ae1eac0440bcee416b40"
transactionHash:"0x13938092bb6663ad1817a0923c947e1ae951402105d10d6ebb041313aedbd51f"
transactionIndex:"0x0"
type:"0x2"
Namely - gasUsed, cumulativeGasUsed, transactionIndex are all (hex) strings. Type does not exist in TransactionReceipt.
I'm getting a bunch of Typescript complaints from this trying to setup my mongoose
Schemas.
Hi there, I have the following code:
const web3 = createAlchemyWeb3(
`https://eth-mainnet.alchemyapi.io/v2/${process.env.NEXT_PUBLIC_ALCHEMY_API_KEY}`
)
const getTokenBalanceWithAlchemy = async (address, tokens) => {
try {
let tokenBalances = await web3.alchemy.getTokenBalances(address, tokens)
return tokenBalances
} catch (error) {
console.error(error)
}
}
getTokenBalanceWithAlchemy("0x87BA155A86Cf63be05445bABB184e327551810F8", ["0x1f9840a85d5af5bf1d1762f925bdaddc4201f984"])
For some reason, the request gives me an error...
index.js?d1cc:41 TypeError: this.decodeParameters is not a function
at ABICoder.decodeParameter (index.js?8fce:273)
at eval (index.js?1558:113)
at Array.map (<anonymous>)
at processTokenBalanceResponse (index.js?1558:111)
at eval (index.js?1558:102)
at step (tslib.es6.js?61e8:102)
at Object.eval [as next] (tslib.es6.js?61e8:83)
at fulfilled (tslib.es6.js?61e8:73)
Can someone help me figure out why this is happening? Thanks!
Hello,
I get a 400 error when calling the getNfts()
More details: "Error: 400:
at https://cdn.jsdelivr.net/npm/@alch/alchemy-web3@latest/dist/alchemyWeb3.min.js:151:19990
at https://cdn.jsdelivr.net/npm/@alch/alchemy-web3@latest/dist/alchemyWeb3.min.js:16:1903
at Object.next (https://cdn.jsdelivr.net/npm/@alch/alchemy-web3@latest/dist/alchemyWeb3.min.js:16:2008)
at a (https://cdn.jsdelivr.net/npm/@alch/alchemy-web3@latest/dist/alchemyWeb3.min.js:16:747)"
Hello,
I'm trying to get the revert reason of a transaction on my frontend.
When using Alchemy I get the error on the screenshot and notice there is no revert reason
.
But on the Alchemy dashboard, I can see the revert reason speed invalid
as expected.
Here's the repo for a reproduction case, just add your api key and give it a shot.
https://github.com/laygir/web3-revert-test/tree/using-alchemy
Following contract is being used for this reproduction case.
contract CallRevert {
uint256 speed;
function Start(uint256 _speedPercent) public {
require(_speedPercent <= 100, 'speed invalid');
speed = _speedPercent;
}
}
When deployed and a transaction sent locally againts Hardhat, here's the result.
*I've tried getting help on Discord but no luck, so creating an issue here.
I've initiated the Alchemy web (version: "@alch/alchemy-web3": "^0.1.18"
) as follows
import { createAlchemyWeb3 } from '@alch/alchemy-web3'
web3 = createAlchemyWeb3('https://eth-mainnet.alchemyapi.io/v2/my-key')
But, I get the following error
Request
{"jsonrpc":"2.0","id":75,"method":"eth_getBlockByNumber","params":[null,false]}
Response
{"jsonrpc": "2.0", "id": 75, "error": {"code": -32602, "message": "Invalid method parameter(s)."}}
Running into Error: Alchemy specific rest endpoints are not available with our legacy endpoints on alchemyapi.io, please switch over to alchemy.com
on version 1.2.1. When I switch the URL, I get FetchError: request to https://eth-mainnet.alchemy.com/REMOVED_PII_API_KEY_FOR_GITHUB/v1/getNFTs/?owner=0xeB94Bd011F6b794B6C846457b85Efa895D2DD744 failed, reason: connect ETIMEDOUT 23.45.205.250:443
This PR seems to also address this issue
#88
A declarative, efficient, and flexible JavaScript library for building user interfaces.
π Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. πππ
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google β€οΈ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.