clbrge / svelte-web3 Goto Github PK
View Code? Open in Web Editor NEWweb3.js library integration as a Svelte store
License: MIT License
web3.js library integration as a Svelte store
License: MIT License
I have this in my App.svelte file:
<script>
import { defaultChainStore, web3, selectedAccount, connected, chainData } from 'svelte-web3'
defaultChainStore.setBrowserProvider()
</script>
I get this error:
[!] Error: 'default' is not exported by node_modules\svelte-web3\src\chains.json, imported by node_modules\svelte-web3\src\web3-store.js
https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module
node_modules\svelte-web3\src\web3-store.js (2:7)
1:
2: import chains from './chains.json'
^
3: import { derived, writable } from 'svelte/store'
Error: 'default' is not exported by node_modules\svelte-web3\src\chains.json, imported by node_modules\svelte-web3\src\web3-store.js
Here is my code:
let cData;
const customChain = makeChainStore('xDai');
customChain.chainData.subscribe(c => cData = c)();
cData is always empty dict
Any idea why?
Thanks
It would be super helpful for blockchain beginners like me if there was an example how to get a custom token balance of an address.
Hello, after I create a store using makeContractStore(ABI, address) I'm unable to call this Contract object from another component in my app. Could you provide an example of how to call and use a contract method from this store? Thank you.
Hey, I'm working on a package and I'm using svelte-web3 as a dependency and I'm getting this problem (it might be on my end but I can't seem to figure it out)
No "exports" main defined in C:\Users\antho\Desktop\Work\Cointrack\Web\cointrack\node_modules\svelte-contracts\node_modules\svelte-web3\package.json imported from C:\Users\antho\Desktop\Work\Cointrack\Web\cointrack\node_modules\svelte-contracts\dist\index.js
Here is the repository: https://github.com/PythoniCode/svelte-contracts
Initially, connected wallet network ID will be represented as decimal integer, so for BSC that would be 56
and ETH 1
But after wallet is opened and the network is switched, the $chainId
produces 0x38
and 0x1
respectively.
I created an app with sveltekit and globaly disabled SSR. I followed the When I try to access the $web3 store, it crashes saying it is not defined. I could not find what I'm doing wrong in the Readme guide
Here is my code:
<script context="module" lang="ts">
export const prerender = true;
</script>
<script lang="ts">
import Board from '$lib/components/board/Board.svelte';
import { onMount } from 'svelte';
import {
defaultChainStore,
web3,
selectedAccount,
connected,
} from 'svelte-web3';
// Connect to metamask
onMount(() => defaultChainStore.setBrowserProvider());
let balance = $web3.eth.getBalance('0x76fc18e74dd215467a5ed990ceb322c94df01de9')
</script>
<svelte:head>
<title>Tic-tac-toe</title>
</svelte:head>
<section>
<h1>Tic-tac-toe</h1>
<Board />
</section>
I am getting the following warning when using Sveltekit and Svelte-Web3. The recommendation from the FAQ is to raise an issue with the library author.
WARNING: The following packages use a svelte resolve configuration in package.json that has conflicting results and is going to cause problems future.
[email protected]
Please see https://github.com/sveltejs/vite-plugin-svelte/blob/main/docs/faq.md#conflicts-in-svelte-resolve for details.
I am having a hard time using this cool lib with Sapper
Here is the error I am getting when I try to import the lib
> sapper dev --ext '.svelte .svx'
✗ client
Assigning to rvalue (Note that you need plugins to import files that are not JavaScript)
43060:
43061: process.title = 'browser';
43062: process.browser = true;
^
43063: process.env = {};
43064: process.argv = [];
• server
✔ service worker (114ms)
.../todo-app/srv/node_modules/svelte-web3/dist/index.js:68538
_btoa = btoa.bind(window);
^
ReferenceError: btoa is not defined
at Object.<anonymous> (.../todo-app/srv/node_modules/svelte-web3/dist/index.js:68538:4)
at Object.439._process (.../todo-app/srv/node_modules/svelte-web3/dist/index.js:68550:5)
at o (.../todo-app/srv/node_modules/svelte-web3/dist/index.js:28:337)
at .../todo-app/srv/node_modules/svelte-web3/dist/index.js:28:388
at Object.440../helpers.js (.../todo-app/srv/node_modules/svelte-web3/dist/index.js:68556:16)
at o (.../todo-app/srv/node_modules/svelte-web3/dist/index.js:28:337)
at .../todo-app/srv/node_modules/svelte-web3/dist/index.js:28:388
at Object.415../batch.js (.../todo-app/srv/node_modules/svelte-web3/dist/index.js:62131:23)
at o (.../todo-app/srv/node_modules/svelte-web3/dist/index.js:28:337)
at .../todo-app/srv/node_modules/svelte-web3/dist/index.js:28:388
btoa
is a browser-only function so I tried sth else by making it client side only i .e SSR compatible but no luck there too
Here is the code I used
onMount( async () => {
const svelteWeb3 = await import('svelte-web3');
const { ethStore, web3, selectedAccount, connected } = svelteWeb3
but then the way the $web3
store is initiatied creates a conflict.
npm run dev 130 ↵
> [email protected] dev .../todo-app/srv
> sapper dev --ext '.svelte .svx'
✗ server
.../todo-app/srv/src/components/Nft.svelte
Stores must be declared at the top level of the component (this may change in a future version of Svelte)
71: // getAccount
72: address = get(selectedAccount)
73: contract = new $web3.eth.Contract(abi, 0x, {
^
74: from: address
75: })
✗ client
.../todo-app/srv/src/components/Nft.svelte
Stores must be declared at the top level of the component (this may change in a future version of Svelte)
71: // getAccount
72: address = get(selectedAccount)
73: contract = new $web3.eth.Contract(abi, 0x, {
^
74: from: address
75: })
internal/modules/cjs/loader.js:1032
throw err;
^
Error: Cannot find module '.../todo-app/srv/__sapper__/dev/server/server.js'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:1029:15)
at Function.Module._load (internal/modules/cjs/loader.js:898:27)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
at internal/main/run_main_module.js:17:47 {
code: 'MODULE_NOT_FOUND',
requireStack: []
}
> Server crashed
Any idea or pointer about how this could be solved?
Many thanks for the lib
I keep getting this error anytime I tried to use the library
Uncaught (in promise) Error: Cannot find Web3
my code example below
`<script>
import { defaultChainStore} from 'svelte-web3'
import { onMount } from 'svelte';
onMount( ()=>{
defaultChainStore.setBrowserProvider()
})
</script>`
Hello
When calling to setProvider
on defaultEvmStores
I get an error
{
"code": 4100,
"message": "The requested account and/or method has not been authorized by the user."
}
The wallet I am using is Metamask.
I have no idea what could be happening, but it seems recently the values provided from chainId
store changed format, perhaps that could be related?
The issue occurs on Opera where I tested the wallet connection before (worked without any problems), and then after a while deployed a new version of the website. Then it stopped working.
On Opera I have Metamask with 2 accounts and 2 networks configured - ETH mainnet and BSC
I have just performed a test with freshly installed Metamask in Chrome, on the same website deployed on the same CDN and it works.
my code is pretty simple, but I'll paste it anyway:
async function unlockWallet() {
await defaultEvmStores.setProvider()
}
this function is called when user is pressing a button.
Can I use this with web3connect https://github.com/web3connect/web3connect ?
I don't know how to add the provider web3connect returns
Hi,
Thank you for the great work on the repo,
a bit new to working with smart contracts in Svelte, apologies for the noob-ish question;
How does one dynamically update the UI (for ex: adding pending and complete transactions as a Svelte component)
Or more formally how does one watch the chain for transfers and transactions?
any plans for a roadmap in the future?
Shouldn't there be a way of enabling calls to ethStore.setProvider(url)
when running in SSR mode?
I would like for my SvelteKit load()
function to execute calls against my contract using the Infura interface. I have tried to initialize using the browser
boolean for the conditional.
ethStore.subscribe(async store => {
if (browser) {
await ethStore.setBrowserProvider();
} else {
await ethStore.setProvider(import.meta.env.VITE_INFURA_ADDRESS);
}
});
Unfortunately, there doesn't seem to be any attempt to instantiate Web3 if it is not already loaded, which will only happen on the browser.
Noticing that store values return an object with subscribe
where we're expected to chain a callback.
Is there an async
await
means of being able to work with the values from web3? I'd like to do operations like determine how many items the user owns for a particular contract
Hi, i was trying to use the web3.eth.sign(dataToSign, address [, callback]) as in the example from the web3 api, like this:
const signature = async (e) => {
console.log('Received event (rec)', e)
const tx = await $web3.eth.sign($selectedAccount, $selectedAccount);
console.log('Receipt from transaction', tx)
alert('Thanks!')
}
the console shows the first log, and then nothing.
i also tried this way with the same result
$web3.eth.sign($selectedAccount, $selectedAccount)
.then(console.log);
when i log the whole code it shows a promise that never gets resolved.
thanks
svelte-web3 is going to get a major upgrade 3.0 in a few days that would probably need a refresh of types declarations.
I'm not using typescript myself. Any volunteer to prepare the ts version ?
@Creskendoll do you want to follow up on your last PR ?
pre release versions are in branch next/components & on npm.
Sorry to open this issue again but I come across this issue when I tried to interact with the contract.
I run the same code as the example
<script>
import { contracts } from 'svelte-web3'
// ...
</script>
{#await $contracts.myContract.methods.totalSupply().call()}
<span>waiting...</span>
{:then value}
<span>result of contract call totalSupply on my contract : { value } </span>
{/await}
Hi, I was working on a web3 game about 10 months ago, and recently came back to it. I am getting the strangest error:
Uncaught (in promise) s: Web3 validator found 1 error[s]:
value "1" at "/0" must pass "hex" validation
This occurs whenever I try to connect, BUT if I switch provider in Metamask it all of a sudden updates and is connected properly.
The number for value changes depending on chainID of the network I've chosen in Metamask.
I've tried:
downgrading web3js to 4.0.3
using web3modal
using default injected
something like
defaultEvmStores.setProvider().then("connected" => //do something)
or
await defaultEvmStores.setProvider() //do something here
because right now it throws no error or anything to indicate that the user didn't connect a address other than checking if $selectedAccount exists
Running svelte-web3 with Metamask, the latter informs that the "close" may be removed in any future version.
MetaMask: The event 'close' is deprecated and may be removed in the future. Please use 'disconnect' instead.
For more information, see: https://eips.ethereum.org/EIPS/eip-1193#disconnect
_warnOfDeprecation @ inpage.js:1
on @ inpage.js:1
u.setProvider @ web3.js:15
e @ web3.js:15
packageInit @ web3.js:3
d @ web3.js:15
set1193Provider @ stores.js:107
await in set1193Provider (async)
setProvider @ stores.js:130
I'm not sure if I'm just not using it right, but I am not seeing it inside of svelte-web3.d.ts either.
When I attempt to run the svelte-app-template as an example I receive this message when compiling and nothing shows.
Use output.globals to specify browser global variable names corresponding to external modules svelte-proxied-store (guessing 'svelteProxiedStore')
If I comment out the modal, mono and multi components the output looks like the following. Did something change in a dependency that I didn't pick up?
Visit the Svelte tutorial to learn how to build Svelte apps.
Visit the Web3.js documentation to learn how to use Web3.js library.
The Web3.js library has been injected in Global window Object (version: 1.7.5).
Browser wallet detected in Global Object window.ethereum : yes
Browser wallet already connected to metamask : true
Hey, I'm trying to see the Modal in Sveltekit and I get a blank modal (maybe because providers aren't loaded?)
So I try to add WalletConnect but it throws an error that globals aren't defined.
So I tried const WalletConnectProvider = await import("@walletconnect/web3-provider");
But after that the error just moves to index.ts:19 instead of the main scope
Edit: It happens with all the external wallets
I'm getting the following error when importing from svelte-web3
exports is not defined
ReferenceError: exports is not defined
Here is more detailed logs
1:04:38 PM [vite] Error when evaluating SSR module /node_modules/svelte-proxied-store/dist/store.js?v=648dcf98:
ReferenceError: exports is not defined
at eval (/node_modules/svelte-proxied-store/dist/store.js?v=648dcf98:5:23)
at instantiateModule (C:\Users\antho\Desktop\Code\Tutorials\MyDapp\node_modules\vite\dist\node\chunks\dep-76613303.js:60094:15)
1:04:38 PM [vite] Error when evaluating SSR module /node_modules/svelte-web3/src/stores.js:
ReferenceError: exports is not defined
at eval (/node_modules/svelte-proxied-store/dist/store.js?v=648dcf98:5:23)
at instantiateModule (C:\Users\antho\Desktop\Code\Tutorials\MyDapp\node_modules\vite\dist\node\chunks\dep-76613303.js:60094:15)
1:04:38 PM [vite] Error when evaluating SSR module /src/routes/index.svelte:
ReferenceError: exports is not defined
at eval (/node_modules/svelte-proxied-store/dist/store.js?v=648dcf98:5:23)
at instantiateModule (C:\Users\antho\Desktop\Code\Tutorials\MyDapp\node_modules\vite\dist\node\chunks\dep-76613303.js:60094:15)
This is when importing from a newly instantiated SvelteKit project. Here is the code in my <script> tag:
// IMPORT THESE
import { browser } from '$app/env';
import { defaultEvmStores, web3, selectedAccount, connected, chainId, chainData } from 'svelte-web3';
// This will only render client-side if the browser is available.
if(browser) {
defaultEvmStores.setBrowserProvider();
}
I didnt see a discussion space so asking them here.
Thanks in advance.
web3js has recently released a major upgrade to v4.x.y
and this library does not seem to be compatible anymore with that version.
The latest version I seem to be able to get compatibility with is v1.3.4
If eg I try to connect to a chain with ID 1071
I get the following error coming from the web3js library added using the cdn (which points to latest).
s: Web3 validator found 1 error[s]: value "1071" at "/0" must pass "hex" validation
If needed I can provide a repository and a deployment url
Thank you very much 🌷
Error: Failed to resolve entry for package "svelte-web3". The package may have incorrect main/module/exports specified in
its package.json: No known conditions for "." specifier in "svelte-web3" package
I'm facing a problem in which when I am refreshing a page, the data is lost.
Hi,
I recently participated in EthLisbon and used svelte-web3
for building the frontend. Other users might find this example useful:
https://github.com/tradingstrategy-ai/frontend/blob/master/src/lib/web3/Investor.svelte
The page is live here:
https://tradingstrategy.ai/strategy/ethlisbon
I can add this also to README or another relevant place for those who want to get up to the speed quick with a ready example.
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.