Git Product home page Git Product logo

docs's People

Contributors

anastasiia-khab avatar brettkolodny avatar crokau avatar drgorb avatar github-actions[bot] avatar jacogr avatar jakai7 avatar jesseabram avatar jhonalino avatar jsidorenko avatar maltekliemann avatar mirooon avatar n3wborn avatar niklasp avatar olitelkes avatar pedroapfilho avatar petermortensen avatar prakharsharma888 avatar raoulmillais avatar ronnyroeller avatar rzadp avatar shawntabrizi avatar sleepingnext avatar tarikgul avatar tarrball avatar tbaut avatar vadimsaveljev avatar vikiival avatar wilwade avatar wirednkod avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

docs's Issues

Problem with app

Hello, i created my wallet today and when i finally sent my dots there the website stopped working. Now its a full white screen

How to get transaction hash?

How to obtain the transaction hash of transactions created through “api.tx.utility.batchAll(calls)” after they are in block.

Creating enums using `createType`

It seems like enums types like this one...

"MyEnum": {
  "_enum": {
    "member": "u32",
    ...
  }
}

...are created using the following pattern:

let enum = api.createType("MyEnum", {"member": value});

Is this correct? If so, I think this is missing from the docs.

Question About Private Key and Derivation

Hello. I'm really sorry if this is due to my lack of knowledge. After reading the documentation for a few days, I still have some questions in my head.

  1. Assume that I have mnemonic words. And then, I use the mnemonicToMiniSecret(mnemonic) function to create a seed. After that, I use the schnorrkelKeypairFromSeed(seed) function to create a keyPair. From the keyPair, I can have a publicKey that has the same value as the publicKey that I can have from the createFromUri(mnemonic) function, and also a secretKey. My question is, "Is the secretKey actually a privateKey that can be used for signing a transaction?". I'm asking this because I need to save the privateKey of the account that I created.

  2. This question is a bit related to the first one. Assume that the first question is answered with a "Yes". In Polkadot, is it possible to use the privateKey of an account as an xprv to generate a childPrivateKey? What I'm talking about is kind of deriving an account via the privateKey of its parent.

  3. This question is related to the previous one. Assume that the previous question is answered with a "Yes". Is that also possible to get the privateKey of that derived account?

Again, I'm really sorry if this is due to my lack of knowledge. Thanks in advance! 😄

wallet-error

could you help with the error:

createType(SignedBlock):: Struct: failed on block: {"header":"Header","extrinsics":"Vec<Extrinsic>"}:: Struct: failed on extrinsics: Vec<Extrinsic>:: createType(ExtrinsicV4):: createType(Call):: Call: failed decoding staking.submitElectionSolutionUnsigned:: Struct: failed on args: {"winners":"Vec<ValidatorIndex>","compact":"CompactAssignments","score":"ElectionScore","era":"EraIndex","size":"ElectionSize"}:: Maximum call stack size exceeded

and as for Maximum call stack size exceeded, do API has some limit? how to solve

unique trxHash

Hi Guys
during sign and send transaction ,how we can get Extrinsic position and block height?
thanks for support

Add JSON export guide to typegen docs

It would be great to have instructions on how to (quickly) generate polkadot-js types to json for development purposes.

e.g. something similar to the following script we created together:

const edgewareDefinitions = require('./dist/definitions.js');

console.log(edgewareDefinitions);

const types = Object
  .values(edgewareDefinitions)
  .reduce((res, { types }) => ({ ...res, ...types }), {});

console.log(JSON.stringify(types));

and add it here (or similar).

Polkadot.js Issues.

When trying to claim my Pswap i keep getting this error. Im logged in with my ledger but it keeps giving me this error msg. Any input appreciated.

Something went wrong with the query and rendering of this component. Unable to find supported chain for 0x7e4e32d0feafd4f9c9414b0be86373f9a1efa904809b683453a9af6856d38ad5

 

 

Error: account balance too low

transfer dot error:

Error: 1010: Invalid Transaction: Inability to pay some fees , e.g. account balance too low

fromAddress has amount 1dot

// params= > fromkey, toaddr, (10000000000 - 154000000)
async function test_sendDotWithRpc(fromKey, toAddr, amount) {
    await api.isReady;
    let keyring = new Keyring();
    let suri = fromKey;
    let pair = keyring.addFromUri(suri);
    // single
    let transfer = api.tx.balances.transfer(toAddr, amount);
    let txhash = await transfer.signAndSend(pair, { nonce: -1 }).catch(console.error);
    console.log('txhash->', txhash.toHex(), amount);
}

could I get any more information for what happened?
why this error

Getting started stumbling blocks

I have just rolled through the Getting Started section in tandem with the Substrate intro tutorial. Awesome work on the platform and the docs BTW, it was really fun to get straight in and have a jam.

Some constrictive feedback:
As a newcomer to blockchain tech in general, I stumbled on the Transactions / Keyring section. I would suggest putting an even simpler high level primer at the start of the Keyring section to ensure the basic concept of a decentralised identity/wallet is clear. Also a bit more explanation about the demo accounts that are preloaded in the substrate demo node and that they're URI based would be helpful for the uninitiated amongst us.

Again, thanks for all the awesome work on this!

Adding Search

I would like to be able to search the documentation on the site.

api.query.staking.currentPlannedSession is not a function

This function works for Kusama but not for Polkadot:

api.query.staking.currentPlannedSession()
TypeError: api.query.staking.currentPlannedSession is not a function

My work-around is to use api.query.session.currentIndex which works for both

Cannot find information about how to run the examples

I am not sure if there is a page that I have not seen, but I cannot figure out how to run any of the examples. For example:

On this page: https://polkadot.js.org/docs/api/examples/promise

It says: "From each folder, run yarn to install the required dependencies and then run yarn start to execute the example against the running node."

Which "folder" is it talking about? Is there a source repository containing all the examples somewhere? Obviously when I run "yarn" from an empty directory, nothing useful happens.

Looking at this page: https://polkadot.js.org/docs/api/start/install

It says "just install the API via:"

yarn add @polkadot/api

However, all this does is give a barebones project which is not enough to run the example code given in the other pages.

Please add information explaining how to run the examples given in this documentation.

How to get extrinsic hash after transfer

i am transferring dot with below code but all i am getting is block hash, how can i get transfer balance extrinsic hash to use in explorer? i can print some hashes in console but none of them is transfer balance extrinsic hash, all i need is extrinsic hash in below link:
https://polkadot.subscan.io/extrinsic/5020030-1

    await api.tx.balances
        .transfer(to_address, amount)
        .signAndSend(sender_pairs, {nonce}, ({events = [], status}) => {
            console.log('status:', status.hash.toHex());
            console.log('status:', status.type.toString());
            if (status.isInBlock) {
                events.forEach(({event: {data, method, section}, phase}) => {
                    console.log('\t', phase.toString(), `: ${section}.${method}`, data.toString(), data.hash.toHex());
                });
            } else if (status.isFinalized) {
                    console.log('Finalized block hash', status);
                process.exit(0);
            }
        })

Add more information to Custom RPC Documentation

I was trying to implement a custom RPC for the substrate node. The documentation provided here does not say to name the RPC as "module_rpcName" in the rust side of things. If we don't, it will not decorate the RPCs.

It was tough for me to figure out the problem. Finally, I found it from this issue: polkadot-js/api#1668

It would be nice if we mention it in the PolkadotJS API Docs

Question about Transaction Fee

Hello. Thank you for reading this issue. Is that possible for a transaction to cost nothing in Polkadot or Westend? For example, sending some DOTs or WNDs to a parent address (The address that derives an address) costs zero fees. Any comments or suggestions are accepted. Thanks in advance!

How to get the amount of transaction of type 'transfer_all'?

Hey, I've been struggling with finding a way to get the amount of transaction that was executed with "Transfer the full account balance, reap the sender" option. I use the RPC API without polkadot-js lib, and basically for every block I just make a "chain_getBlock" call, get the raw extrinsics from it and then decode them to JSON via TypeRegistry.createType('Extrinsic', tx).toHuman() and there I can get transaction method, sender\receiver and the value. However, in 'transferAll' transactions, there is no tx.method.args.value field, and there doesn't seem to be any endpoint in RPC API that allows to get that value. Am I missing something?

Issues while reading from the contract via an RPC call

Hi, I am new to the substrate and Polkadot.

I followed the below link to read from the contract via an RPC call.
https://polkadot.js.org/docs/api-contract/start/contract.read/
The contract deployed is the flip contract that flips the boolean value.
https://substrate.dev/substrate-contracts-workshop/#/0/setup

The contract has been successfully deployed and the flip function was called. I am getting all results in Explorer block details.
But trying to retrieve the contract value by node js gives me output as null and message: 'NotCallable'.

Read from the contract via an RPC call
result_1 : {"debugMessage":"","gasConsumed":0,"output":null,"result":{"Err":{"Module":{"index":17,"error":12,"message":"NotCallable"}}}}
gasConsumed : 0
result : { Err:
{ Module: { index: '17', error: '12', message: 'NotCallable' } } }
Error Type {
registry: MetaRegistry { metaTypeDefs: [ [Object] ] },
isOther: [Getter],
asOther: [Getter],
isCannotLookup: [Getter],
asCannotLookup: [Getter],
isBadOrigin: [Getter],
asBadOrigin: [Getter],
isModule: [Getter],
asModule: [Getter] }

.

Link to apps missing on the polkadot.js.org landing page

Currently the polkadotJS landing page redirects to /docs. There is no mention or linking to apps, which could be confusing to our users, since polkadotJS is often the primary wallet and interface for Polkadot, Kusama and other Substrate chains.

system.events() does not take any arguments

Hello. I just tried the example given in this link: https://polkadot.js.org/docs/api/cookbook/blocks on the question: "How do I map extrinsics to their events?". The line below:
const allRecords = await api.query.system.events(signedBlock.block.header.hash);
seems to need to be changed since system.events() does not take any arguments (Please see image below).
image

Furthermore, how can I get events of a specific block?

Typescipt Error : Property 'data' does not exist on type 'EventRecord'.ts(2339)

this snippet of code that is found on the https://polkadot.js.org/docs/api/cookbook/tx#how-do-i-get-the-decoded-enum-for-an-extrinsicfailed-event will fail in TS using the latest stable and beta version of the api:

api.tx.balances
  .transfer(recipient, 123)
  .signAndSend(sender, ({ status, events }) => {
    if (status.isInBlock || status.isFinalized) {
      events
        // find/filter for failed events
        .filter(({ event: { section, method } }) =>
          section === 'system' &&
          method === 'ExtrinsicFailed'
        )
        // we know that data for system.ExtrinsicFailed is
        // (DispatchError, DispatchInfo)
        // >>>> here it will be ERROR: Property 'data' does not exist on type 'EventRecord'.ts(2339)
        .forEach(({ data: [error, info] }) => {
          if (error.isModule) {
            // for module errors, we have the section indexed, lookup
            const decoded = api.registry.findMetaError(error.asModule);

           // >>>>>  and here Property 'method' does not exist on type 'RegistryError'.ts(2339)
            const { documentation, method, section } = decoded;

            console.log(`${section}.${method}: ${documentation.join(' ')}`);
          } else {
            // Other, CannotLookup, BadOrigin, no extra info
            console.log(error.toString());
          }
        });
    }
  });

It seems there are plenty of changes and no way of getting the error from the ExtrinsicFailed event.

Unless there is an bug in the code and the line .forEach(({ data: [error, info] }) => { should look like .forEach(({event: { data: [error, info] }}) => { or nicety written :

.forEach(({ event }) => {
  const { data } = event;
  const [error, info] = data;

  // >>>> Error : Property 'isModule' does not exist on type 'Codec'.ts(2339)
  if (error.isModule) {
    // for module errors, we have the section indexed, lookup

    // and when the ^^ is resolved 
    // >>> Error: Property 'asModule' does not exist on type 'Codec'.ts(2339)
    const decoded = api.registry.findMetaError(error.asModule);
    // ERROR:  Property 'method' does not exist on type 'RegistryError'.ts(2339)
    const { documentation, method, section } = decoded;

    console.log(`${section}.${method}: ${documentation.join(" ")}`);
  } else {
    // Other, CannotLookup, BadOrigin, no extra info
    console.log(error.toString());
  }
});

in which case it will throw more errors and not being able to compile. currently i am using the terrible trick error['isModule'] which i don't like and i hoped to see it fixed in the v2.

Test repo is here https://github.com/woss/test-polkadot-api

code.createBlueprint is not a function

Hello, I'm trying to work through the examples at https://polkadot.js.org/docs/api-contract/start/code/ and am getting the error "code.createBlueprint is not a function"

I'm using "@polkadot/api-contract": "^4.13.1"

I'm using ink! and attempting to work with the incrementer example contract.

I am using an unmodified substrate canvas chain.

I can execute const code = new CodePromise(api, abi, wasm); without any error.

I'm using var abi = HERE DOC about 300 lines of JSON text from incrementer's metadata.json file and this appears to parse correctly.

I'm using var wasm = "0x... about 36K of hex" from incrementer.contract and this also appears to be working correctly.

If I search the source code for createBlueprint I see about 10 references to createBluePrintTx, but if I try to use this method instead, I get the same error.

Any clues greatly appreciated. Thanks!

how to get out all dot from the address?

Failed at this way:

// totalAmount
let info = await api.tx.balances.transferKeepAlive(toAddr, amount).paymentInfo(pair);
// fee
let fee = info.partialFee.toNumber();
// sendAmount - totalAmount - fee
let transfer = api.tx.balances.transferKeepAlive(toAddr, amount-fee);
let txhash = await transfer.signAndSend(pair);

sendAmount = totalAmount - fee.
why tx on-chain is always failed...

await is only valid in async function & apiPromise not returning anything

As instructed in the local documentation, I ran:

const { ApiPromise } = require('@polkadot/api/promise');

const api = await ApiPromise.create();

api.rpc.chain.subscribeNewHeads().subscribe((header) => {
    console.log(`Chain is at #${header.number}`);
});

And got the output:
SyntaxError: await is only valid in async function


So, I tried to wrap the API in an async function.

const { ApiPromise } = require('@polkadot/api/promise');

async function createApi() {
    return await ApiPromise.create();
}

const api = createApi();
console.log("api = ", api);

api.rpc.chain.subscribeNewHeads().subscribe((header) => {
    console.log(`Chain is at #${header.number}`);
});

But this code gave me an output of:
TypeError: Cannot read property 'chain' of undefined

and a console.log output of:

api =  Promise {
  <rejected> TypeError: Cannot read property 'create' of undefined
      at createApi (C:\Users\Sarah\Documents\GitHub\Latest Block CLU Polkadot\apiPromise.js:4:29)      at Object.<anonymous> (C:\Users\Sarah\Documents\GitHub\Latest Block CLU Polkadot\apiPromise.js:7:13)
      at Module._compile (internal/modules/cjs/loader.js:1133:30)
      at Object.Module._extensions..js (internal/modules/cjs/loader.js:1153:10)
      at Module.load (internal/modules/cjs/loader.js:977:32)
      at Function.Module._load (internal/modules/cjs/loader.js:877:14)
      at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)        
      at internal/main/run_main_module.js:18:47
}

Finally, I tried putting const api = await createApi(); instead of const api = createApi();

const { ApiPromise } = require('@polkadot/api/promise');

async function createApi() {
    return await ApiPromise.create();
}

const api = await createApi();

But this brought me back to where I started...
SyntaxError: await is only valid in async function

Failed on the first time with a simple example

Just running a docker node and run a simple example here https://polkadot.js.org/docs/api/start/create

const { ApiPromise, WsProvider } = require('@polkadot/api');

const wsProvider = new WsProvider('ws://127.0.0.1:9944');

(async () => {
  const api = await ApiPromise.create({ provider: wsProvider });

  // Do something
  console.log(api.genesisHash.toHex());
})();

Got tons of strange errors :(

2021-05-27 15:08:27        REGISTRY: Unable to resolve type ChainId, it will fail on construction
2021-05-27 15:08:27        REGISTRY: Unable to resolve type DepositNonce, it will fail on construction
2021-05-27 15:08:27        REGISTRY: Unable to resolve type ResourceId, it will fail on construction
2021-05-27 15:08:27        API/INIT: Error: FATAL: Unable to initialize the API: createType(ChainId):: Cannot construct unknown type ChainId

transaction

when i push a transaction with the api and set value to 1.0 there is only 0.0000000001 dot transferred is there a way to transfer full dots beside multiplying with 10^10

Memory leak caused due to create too many instances of Api object

Currently every instance of the Api object will create and maintain a web socket connection.
It never disconnects itself and will attempt to reconnect if connection dropped for any reason.

We have an issue that developers are not aware of this behavior and construct a new instance of Api on every method call.
Because the Api object can never automatically GC'ed by JS due to the fact the ws connection is open, this results connection leaks, memory leaks, and unstable application.

I don't know what is the best way to solve this issue other than code review.
I wonder if have polkadot.js enforce shared Api object will help. i.e. have a shared pool of all created api instances, return existing one if parameters (ws url) matches.

typegen sample missing types from '@polkadot/types/lookup' import

When using the typegen on our alphanet network

curl -H "Content-Type: application/json" \
  -d '{"id":"1", "jsonrpc":"2.0", "method": "state_getMetadata", "params":[]}' \
  https://rpc.api.moonbase.moonbeam.network \
  > metadata-alphanet.json

It generates the interface correctly but the types used (in query.ts for exemple) or not imported from from '@polkadot/types/lookup'

Enum decoding Error: Unable to decode storage decodeU8 : Cannot construct unknown type null

I am getting an error while decoding enums using polkadot.js/api version 7.9.1

This is the full decoding error i am getting

  DRR: Unable to decode storage decodeU8a: failed at 0x009001701220099003ddbbdfb0f41f0d… on tokenB:: DoNotConstruct: Cannot construct unknown type null

The tokenB is of type AssetId where,
This is how the type is defined in the rust side.

pub enum AssetId {
    POLKADOT,
    Asset(u64),
}

This is how i defined it on the extended types on javascript

 AssetId: {
    _enum: {
      One: null,
      Two: "u64",
    },
  }

am i doing anything wrong here . This was working in the older version 6.3.1 where i used the js enum as

 AssetId: {
    _enum: {
      POLKADOT: null,
      Asset: "u64",
    },
  }

But is failing with the new 7.9.1 version.

get raw seed

how can i get raw seed from mnemonic? i am generating address and pair like below, but i could not find any method to extract raw seed

let mn = mnemonicGenerate(24)
	const pair = keyring.addFromMnemonic(mn)
	keyring.setSS58Format(0)
	console.log('Address:', pair.address)

but what about raw seed?
i know using mnemonic is suggested but i need to have raw seed like 0x123456789...

Ambiguous Sentence

Hello, I'm sorry if this is due to my lack of knowledge. But, I'm kinda confused with the information provided by https://polkadot.js.org/docs/ui-keyring/start/init in the Create section. It firstly said that the default value is sr25519. But, at the end of the sentence, it says the default value is ed25519 (Please the image attached in this issue). If the default is ed25519, you might consider saying: "Sets up the default account type to sr25519", just like the above one did. Thank you very much :)

image

How to query for the number of validators waiting to get into the set?

Not sure if this is the place to ask for help on API usage, but could not find link in the docs for a recommended community, perhaps there will be a stack exchange category soon. Anyway:

I am trying to figure out how to snapshot the actual number of validators running, i.e. not just the active validator set, but also any validators running, trying to get into the validator set, but did not have enough nominations for the current era. The background is that I'm trying to make a power consumption approximation of Polkadot in order to showcase how much better Polkadot is than its contenders. Not really sure what I am doing, mainly a learning project to get a grasp of Substrate.

The question is, where to do this in the API? Getting the active validators is easy with
api.query.session.validators() but how can I get the ones that did not make it into the set.

RECEPTION DOT

j ai envoyé des DOT sur mon extension en prenant soin de bien choisir POLKADOT RELAY CHAIN mais comment savoir si il est bien crédité, de plus quand je le connecte a ACALA j ai une page BLANCHE

SyntaxError: Cannot use import statement outside a module '@polkadot/util-crypto'

So I came up with this issue when trying to use '@polkadot/util-crypto', I provided a .zip file with a simplified code version displaying the same error I have. I tried the solutions showed in the error message without success and then I started messing around with jest.config without success either. I would very much appreciate help on that matter and I thank in advance anyone who would help me with this.

Here is roughly the error message I get:

   Test suite failed to run

    Jest encountered an unexpected token

    This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.

    By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".

    Here's what you can do:
     • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/en/ecmascript-modules for how to enable it.
     • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
     • If you need a custom transformation specify a "transform" option in your config.
     • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/en/configuration.html

    Details:

    /Users/luc/Documents/infrastructure/lib/services/blockchain-wallets/polkadot-wallet/node_modules/@polkadot/util-crypto/index.js:3
    import "./cryptoInit.js";
    ^^^^^^

    SyntaxError: Cannot use import statement outside a module
    > 1 | import {signatureVerify} from '@polkadot/util-crypto'
       2 | ^

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1350:14)
      at Object.<anonymous> (src/polkadot-signer.ts:11:1)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        2.646 s
Ran all test suites matching /spec/i.

polkadot-wallet.zip

TypeError: Cannot read property 'claim' of undefined

const utx = api.tx.claims.claim(beneficiary, ethSignature);

console:
TypeError: Cannot read property 'claim' of undefined
at main (D:/polkadot_test/polkadot_staking_transfer_test/transfer_multi.js:24:27)
at processTicksAndRejections (internal/process/task_queues.js:97:5)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.