Git Product home page Git Product logo

txwrapper's Introduction



@substrate/txwrapper

Helper funtions for offline transaction generation.

npm Github Actions apache-2.0 david-dm



DEPRECATION NOTICE

On 9 June 2021 this repo will stop being supported.

Please use txwrapper-polkadot instead of this package for long term support and more features. This package will be phased out in the future in favor of the packages in txwrapper-core.

If you are a chain builder looking to build a chain specific txwrapper please take a look at txwrapper-core and the guide for chain builders.

Get Started

yarn add @substrate/txwrapper

In a JS/TS file:

import {
  createSignedTx,
  createSigningPayload,
  methods,
} from '@substrate/txwrapper';

const unsigned = methods.balance.transfer(
  {
    dest: 'FoQJpPyadYccjavVdTWxpxU7rUEaYhfLCPwXgkfD6Zat9QP',
    value: 100,
  },
  {
    // Additional information needed to construct the transaction offline.
  }
);

const signingPayload = createSigningPayload(unsigned, { registry });
// On your offline device, sign the payload.
const signature = myOfflineSigning(signingPayload);

// `tx` is ready to be broadcasted.
const tx = createSignedTx(unsigned, signature, { metadataRpc, registry });

Have a look at the examples to see how you can perform the whole lifecycle of a transaction, from generation to signing to broadcast.

Go to documentation to see all available functions.

Contribute

We welcome contributions. Before submitting your PR, make sure to run the following commands:

  • yarn docs: Will generate docs based on code comments.
  • yarn test: Make sure all tests pass.
  • yarn lint: Make sure your code follows our linting rules. You can also run yarn lint --fix to automatically fix some of those errors.

Note for Maintainers

All the commits in this repo follow the Conventional Commits spec. When merging a PR, make sure 1/ to use squash merge and 2/ that the title of the PR follows the Conventional Commits spec.

The history of commits will be used to generate the CHANGELOG. To do so, run yarn deploy on the master branch. This command will look at all the commits since the latest tag, bump the package version according to semver rules, and generate a new CHANGELOG.

If you don't want to follow semver or need to do a dry run, consult the standard-version CLI usage docs. Flags for standard-version can be passed to yarn deploy.

yarn deploy, which only does local operations and doesn't push anything, will output more or less the following lines:

$ yarn deploy
yarn run v1.21.1
$ yarn build && standard-version -r minor
$ rimraf lib/ && tsc
✔ bumping version in package.json from 0.3.2 to 0.4.0
✔ outputting changes to CHANGELOG.md
✔ committing package.json and CHANGELOG.md
✔ tagging release v0.4.0
ℹ Run `git push --follow-tags origin master && npm publish` to publish

To publish the new package, run: git push --follow-tags origin master && npm publish. You must have access to the @substrate organization on npm to publish.

Roadmap

  • API revamp to clarify handling of registry and metadataRpc.

Parachain support

  • Factor out utility functions and types (such as decode, getRegistry, createMethod etc) into a library for parachain teams that allows them to release and maintain txwrapper libraries specific to their parachains. This could be called @substrate/txwrapper-core. This lib will allow a parachain team to set up an offline signing lib with unit tests quickly and painlessly while allowing users access to a consistent txwrapper API across parachains.
  • While the core utility will be factored out to its own dependency, dispatchables from generic substrate methods will be published in a package @substrate/txwrapper-substrate and Polkadot/Kusama specific dispatchables will be available in @substrate/txwrapper-polkadot. (This could be in a mono repo, but separate packages.) Parachains then create their own txwrapper lib using the txwrapper-core and publish it as @{parachain-name}/txwrapper.

txwrapper's People

Contributors

amaury1093 avatar axelchalon avatar dependabot-preview[bot] avatar dependabot[bot] avatar dvdplm avatar emostov avatar github-actions[bot] avatar joepetrowski avatar maciejhirsz avatar psiofxt avatar tarikgul avatar tripleight 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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

txwrapper's Issues

Unable to run example with node-template

While trying to run example substrateMaster.ts, i get the following error

Error: 1002 Verification Error: Execution: Could not convert parameter `tx` between node and runtime: No such variant in enum MultiSignature: "RuntimeApi(\"Execution: Could not convert parameter `tx` between node and runtime: No such variant in enum MultiSignature\")"

It originates at await rpcToNode('author_submitExtrinsic', [tx]); in the example.

I tried setting the types as below but same error.

registry.setKnownTypes({
    types: {
      "Address": "AccountId",
      "LookupSource": "AccountId",
      "Balance": "u64",
      "BlockNumber": "u32",
      ............
      ................

I see a similar issue from the past but apparently, its cause is already fixed.

poldot tokenDecimals 10 not 12 ,send tx error

Polkadot: { ss58Format: constants_1.POLKADOT_SS58_FORMAT, tokenDecimals: 12, tokenSymbol: 'DOT', },

Polkadot 10????
send unit eror ,,
// 10 000 000 000 ok ,
// 100 000 000 000 false

Add param to decode for address encoding

Right now, the decode suite of functions always returns addresses in Kusama encoding. Add a parameter to the function so the user can select the address format.

Cannot install with NPM when added as github dependency

For my JS project, I cannot use yarn and have to use NPM in my project and I wanted to specify txwrapper as a GitHub dependency but because of the files field in package.json, npm considers only the lib folder (for more check here). Is it possible to remove that field?
For reference, i removed it here and then specified it as GH dependency and a postinstall script in my package.json like below (I see its not cross platform) and I am able to use it.

"scripts": {
    .......,
    "postinstall": "cd node_modules/@substrate/txwrapper && npm run build && cd -"
},

"dependencies": {
     "@substrate/txwrapper": "github:lovesh/txwrapper#with-npm",
....
}

Running code like the example gives an error

This is my code, When I run the transfer, an error occurs
Error: Struct: failed on 'metadata':: Cannot map Enum JSON, unable to find 'registry' in v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11,

I can’t find the problem. Can you plaese help me? I’ve been working on the offline transaction body for a week. No one is willing to reply to the issue of polkadot now. I’m so happy to see the offline method here. I hope you can help me

...

        const { block } = await api.rpc.chain.getBlock();
        const blockHash =  await api.rpc.chain.getBlockHash(block.header.number);
        const genesisHash =  await api.rpc.chain.getBlockHash(0);
        const metadataRpc = await api.rpc.state.getMetadata();
        const nonce = (await api.query.system.account('5FA5GKjtaCYHRhLtJ8bWhA1zP137PzTMmiDw8nfb5wDXSyGD')).nonce;
        const { specVersion, transactionVersion } = await api.rpc.state.getRuntimeVersion();
        const registry = getRegistry('Westend', 'Westend', specVersion, metadataRpc);
        const unsigned = methods.balances.transfer(
            {
                value: 7,
                dest: '5GXvoYbSd2VZeabSY63mGdGJc6bDrmZg5mTz78ueEhKMAivm',
            },
            {
                address: '5FA5GKjtaCYHRhLtJ8bWhA1zP137PzTMmiDw8nfb5wDXSyGD',
                blockHash,
                blockNumber: registry
                    .createType('BlockNumber', block.header.number)
                    .toNumber(),
                eraPeriod: 64,
                genesisHash,
                metadataRpc,
                nonce, // Assuming this is Alice's first tx on the chain
                specVersion,
                tip: 0,
                transactionVersion,
            },
            {
                metadataRpc,
                registry,
            }
        );

Different `registry` return different `signingPayload`

I accidentally creating signingPayload by using another registry since I thought I can do it. The result is it creating incorrect payload that I can not submit to network. Here is the reproduce code:

import * as api from '@polkadot/api';
import * as util from '@polkadot/util';
import * as txwrapper from '@substrate/txwrapper';
import axios from 'axios';

const url = 'http://localhost:8080';

async function main() {
	const material = (await axios.get(`${url}/transaction/material`))
		.data as Record<string, any>;

	const keyring = new api.Keyring();
	const alice = keyring.addFromUri('//Alice', { name: 'Alice' }, 'ecdsa');

	const registry = txwrapper.getRegistry(
		material.chainName,
		material.specName,
		Number(material.specVersion),
	);

	const unsigned = txwrapper.methods.balances.transfer(
		{
			value: '10000',
			dest: '5DpGPTju2gHJKo8cjWRGwzyUPKHBkGVm7d9HH6XUyn5qi1p6', // random address
		},
		{
			tip: 0,
			nonce: 2,
			address: alice.address,
			eraPeriod: 10000,
			blockNumber: Number(material.at.height),
			blockHash: material.at.hash,
			genesisHash: material.genesisHash,
			metadataRpc: material.metadata,
			specVersion: Number(material.specVersion),
			transactionVersion: Number(material.txVersion),
		},
		{
			registry,
			metadataRpc: material.metadata,
		}
	);

	const extrinsicPayload = registry.createType(
		'ExtrinsicPayload',
		unsigned,
		{
			version: 4,
		}
	).toU8a({ method: true });

        const anotherRegistry = txwrapper.getRegistry(
		material.chainName,
		material.specName,
		Number(material.specVersion),
	);
        const anotherExtrinsicPayload = anotherRegistry.createType(
		'ExtrinsicPayload',
		unsigned,
		{
			version: 4,
		}
	).toU8a({ method: true });

        console.log('These payload are different:');
        console.log('extrinsicPayload:', util.u8aToHex(extrinsicPayload));
        console.log('anotherExtrinsicPayload:', util.u8aToHex(anotherExtrinsicPayload)); // This one will always fail after sign and submit to network
}

main().catch(console.log);

Is this behavior expected?

Add governance calls

Add the following dispatchable functions from democracy:

  • set_proxy
  • resign_proxy
  • remove_proxy
  • proxy_vote
  • vote

Decoded tx is not backward compatible

With v3.10.10 when decoding a signed hash the result looks like this.

{
  metadataRpc: '',
  method: { 
    args: {
      dest: { Id: '13W9f1t...' },
      value: 10000,
    },
    name: 'transferKeepAlive',
    pallet: 'balances'
  },
  nonce: 218,
  tip: 0,
}

With v3.10.0 it looks like this:

{
  metadataRpc: '',
  method: { 
    args: {
      dest: '13W9f1t...', // Dest in the newest version is an object instead of string
      value: 10000,
    },
    name: 'transferKeepAlive',
    pallet: 'balances'
  },
  nonce: 218,
  tip: 0,
}

It kind of breaks our system

metadata when running offline

Since this lib is intended to work offline, does this means polkadot metadata could be provided staticly? or it's suggested to retrieve updated metadata on every run?

Can not verify signature when using ecdsa keys

Get Expected signature with 65 bytes, 66 found instead when trying to verify the signature with a transfer tx payload. I think it related to the extra TYPE_PREFIX byte prepend to signature after signing. Here is my example code:

const api = require('@polkadot/api');
const util = require('@polkadot/util');
const fetch = require('node-fetch');
const txWrapper = require('@substrate/txwrapper');
const utilCrypto = require('@polkadot/util-crypto');

const url = 'http://localhost:8080';

async function main() {
  // Api is provided by subtrate-api-sidecar, so you might want to input your own material data
  const material = await (await fetch(`${url}/transaction/material/`)).json();
  const keyring = new api.Keyring();
  const alice = keyring.addFromUri('//Alice', { name: 'Alice' }, 'ecdsa');
  const registry = txWrapper.getRegistry(material.chainName, material.specName, Number(material.specVersion));
  const unsigned = txWrapper.methods.balances.transfer({
    value: '10000',
    dest: '5DpGPTju2gHJKo8cjWRGwzyUPKHBkGVm7d9HH6XUyn5qi1p6', // random address
  }, {
    tip: 0,
    nonce: 2,
    address: alice.address,
    eraPeriod: 10000,
    blockNumber: Number(material.at.height),
    blockHash: material.at.hash,
    genesisHash: material.genesisHash,
    metadataRpc: material.metadata,
    specVersion: Number(material.specVersion),
    transactionVersion: Number(material.txVersion),
  }, {
    registry,
    metadataRpc: material.metadata,
  });

  const signing = txWrapper.createSigningPayload(unsigned, { registry });
  const { signature } = registry.createType('ExtrinsicPayload', signing, { version: 4 }).sign(alice);
  console.log(alice.verify(util.u8aToU8a(signing), util.u8aToU8a(signature)));
}

main().catch(console.log);

And here is the error:

Error: Expected signature with 65 bytes, 66 found instead
    at assert (/Users/admin/test/node_modules/@polkadot/util/assert.js:34:11)
    at secp256k1Verify (/Users/admin/test/node_modules/@polkadot/util-crypto/secp256k1/verify.js:30:20)
    at Object.ecdsa (/Users/admin/test/node_modules/@polkadot/keyring/pair/index.js:52:55)
    at Object.verify (/Users/admin/test/node_modules/@polkadot/keyring/pair/index.js:199:54)
    at main (/Users/admin/test/example.js:35:21)
    at process._tickCallback (internal/process/next_tick.js:68:7)

Transaction has a bad signature

Use the example to create a transaction, and the broadcast fails。
https://github.com/paritytech/txwrapper/blob/master/examples/polkadot.ts

My DOT address is ‘15MmSw7MC8XSv1HoY1G2pYkpS1qQ4yA43fydBd9MEXfnVZ9Y’, there is enough balance in the account。

Below is my code:

import { ApiPromise, WsProvider } from '@polkadot/api';
import { methods, createSigningPayload, createSignedTx } from '@substrate/txwrapper';

let keyring = new Keyring({ ss58Format: 0, type: 'sr25519' });
const keypair = keyring.addFromUri('*******');

const provider = new WsProvider('wss://rpc.polkadot.io');
let api = await ApiPromise.create({ provider: provider });
let blockInfo = await api.rpc.chain.getBlock();
let blockNumber = blockInfo.block.header.number;
let blockHash = await api.rpc.chain.getBlockHash(blockNumber);
let genesisHash = api.genesisHash;
let specVersionInfo = api.runtimeVersion;
let specVersion = specVersionInfo.specVersion;
let transactionVersion = specVersionInfo.transactionVersion;
let metadataRpc = api.runtimeMetadata.toHex();

const registry =  getRegistry('Polkadot', 'polkadot',specVersion);
registry.setMetadata(createMetadata(registry, metadataRpc));

let txInfo = methods.balances.transferKeepAlive(
    {
        dest: '15MmSw7MC8XSv1HoY1G2pYkpS1qQ4yA43fydBd9MEXfnVZ9Y',
        value: 1000000000,
    },
    {
        address: keypair.address,
        blockHash: blockHash,
        blockNumber: blockNumber,
        genesisHash: genesisHash,
        metadataRpc: metadataRpc,
        nonce: 0,
        specVersion: specVersion,
        tip: 0,
        eraPeriod: 64,
        transactionVersion: transactionVersion
    }, {
    registry: registry,
    metadataRpc: metadataRpc

}

);

let signingPayload = createSigningPayload(txInfo, { registry });

let extrinsicPayload = registry.createType('ExtrinsicPayload', signingPayload, { version: 4 });;
let { signature } = extrinsicPayload.sign(keypair);

const signedTx = createSignedTx(txInfo, signature, { metadataRpc, registry });
console.log('signedTx: ' + signedTx);

Require metadataRpc in `getRegistry`

Currently, getRegistry only sets the metadataRpc on a registry when it is supplied as the 4th, optional param. Instead, it would be better if getRegistry required the metadataRpc.

As it stands, most users assume that getRegistry does all the business logic of setting up a registry. However, if the metadataRpc is not passed in there is still some remaining set up on the registry. Most of the time this happens implicitly in other parts of txwrapper (an example is every transaction method does it:

registry.setMetadata(createMetadata(registry, metadataRpc));
).

The current setup can lead to hard to debug, silent errors for users who do not have an in depth understanding of the inner workings of txwrapper and polakdot-js/api. An example is issue #261 and some tough issues that @joepetrowski has helped debug live.

While this would break the API, from my understanding, I don't think this will break any workflow with txwrapper because users can just get a new registry when they have a different metadataRpc, (or the advanced users may set it themselves).

Implementation wise this would be extremely simple, but it warrants discussion as it would break the API.

Add some Utility functions

NOTE: Tentative, may need this for lazy payouts. Currently confirming.

Add:

  • utility.batch
  • utility.asSub

Update governance proxy functions

paritytech/substrate#4895 introduced new ways of handling proxy accounts. Need to add the following changes:

Unchanged (no action)

  • proxyVote

Name Changes

  • removeProxy is now deactivateProxy
  • resignProxy is now closeProxy
  • setProxy is now activateProxy

Functions to Add

  • openProxy

Protect/Warn Against Validity Periods That Are Too Long

After this PR, BlockHashCount should be exposed in the metadata. This is the maximum validity period in blocks. There should be some check, like:

if BlockHashCount in metadata {
    // ensure validityPeriod < BlockHashCount
} else {
    // log "Warning: maximum validity period unknown for this chain..."
}

staking tx example

Can you share an example of how to create a staking/unstaking transaction?

Usage with yarn berry fails

I'm trying to use this package with yarn berry but am running into an odd issue relating to the below log.

    Qualified path resolution failed - none of the candidates can be found on the disk.

    Source path: /Users/brian/Work/platform-sdk/.yarn/cache/@substrate-txwrapper-npm-3.10.7-5c033123a2-2.zip/node_modules/@substrate/txwrapper
    Rejected candidate: /Users/brian/Work/platform-sdk/.yarn/cache/@substrate-txwrapper-npm-3.10.7-5c033123a2-2.zip/node_modules/@substrate/txwrapper
    Rejected candidate: /Users/brian/Work/platform-sdk/.yarn/cache/@substrate-txwrapper-npm-3.10.7-5c033123a2-2.zip/node_modules/@substrate/txwrapper/lib/index.js
    Rejected candidate: /Users/brian/Work/platform-sdk/.yarn/cache/@substrate-txwrapper-npm-3.10.7-5c033123a2-2.zip/node_modules/@substrate/txwrapper/lib/index.js.ts
    Rejected candidate: /Users/brian/Work/platform-sdk/.yarn/cache/@substrate-txwrapper-npm-3.10.7-5c033123a2-2.zip/node_modules/@substrate/txwrapper/lib/index.js.tsx
    Rejected candidate: /Users/brian/Work/platform-sdk/.yarn/cache/@substrate-txwrapper-npm-3.10.7-5c033123a2-2.zip/node_modules/@substrate/txwrapper/lib/index.js.js
    Rejected candidate: /Users/brian/Work/platform-sdk/.yarn/cache/@substrate-txwrapper-npm-3.10.7-5c033123a2-2.zip/node_modules/@substrate/txwrapper/lib/index.js.jsx
    Rejected candidate: /Users/brian/Work/platform-sdk/.yarn/cache/@substrate-txwrapper-npm-3.10.7-5c033123a2-2.zip/node_modules/@substrate/txwrapper/lib/index.js.json
    Rejected candidate: /Users/brian/Work/platform-sdk/.yarn/cache/@substrate-txwrapper-npm-3.10.7-5c033123a2-2.zip/node_modules/@substrate/txwrapper/lib/index.js.node
    Rejected candidate: /Users/brian/Work/platform-sdk/.yarn/cache/@substrate-txwrapper-npm-3.10.7-5c033123a2-2.zip/node_modules/@substrate/txwrapper.ts
    Rejected candidate: /Users/brian/Work/platform-sdk/.yarn/cache/@substrate-txwrapper-npm-3.10.7-5c033123a2-2.zip/node_modules/@substrate/txwrapper.tsx
    Rejected candidate: /Users/brian/Work/platform-sdk/.yarn/cache/@substrate-txwrapper-npm-3.10.7-5c033123a2-2.zip/node_modules/@substrate/txwrapper.js
    Rejected candidate: /Users/brian/Work/platform-sdk/.yarn/cache/@substrate-txwrapper-npm-3.10.7-5c033123a2-2.zip/node_modules/@substrate/txwrapper.jsx
    Rejected candidate: /Users/brian/Work/platform-sdk/.yarn/cache/@substrate-txwrapper-npm-3.10.7-5c033123a2-2.zip/node_modules/@substrate/txwrapper.json
    Rejected candidate: /Users/brian/Work/platform-sdk/.yarn/cache/@substrate-txwrapper-npm-3.10.7-5c033123a2-2.zip/node_modules/@substrate/txwrapper.node
    Rejected candidate: /Users/brian/Work/platform-sdk/.yarn/cache/@substrate-txwrapper-npm-3.10.7-5c033123a2-2.zip/node_modules/@substrate/txwrapper/index.ts
    Rejected candidate: /Users/brian/Work/platform-sdk/.yarn/cache/@substrate-txwrapper-npm-3.10.7-5c033123a2-2.zip/node_modules/@substrate/txwrapper/index.tsx
    Rejected candidate: /Users/brian/Work/platform-sdk/.yarn/cache/@substrate-txwrapper-npm-3.10.7-5c033123a2-2.zip/node_modules/@substrate/txwrapper/index.js
    Rejected candidate: /Users/brian/Work/platform-sdk/.yarn/cache/@substrate-txwrapper-npm-3.10.7-5c033123a2-2.zip/node_modules/@substrate/txwrapper/index.jsx
    Rejected candidate: /Users/brian/Work/platform-sdk/.yarn/cache/@substrate-txwrapper-npm-3.10.7-5c033123a2-2.zip/node_modules/@substrate/txwrapper/index.json
    Rejected candidate: /Users/brian/Work/platform-sdk/.yarn/cache/@substrate-txwrapper-npm-3.10.7-5c033123a2-2.zip/node_modules/@substrate/txwrapper/index.node

When unpacking the file /Users/brian/Work/platform-sdk/.yarn/cache/@substrate-txwrapper-npm-3.10.7-5c033123a2-2.zip it only contains the package.json, README and LICENSE but is missing the lib folder but I'm not sure why it would be missing as I unpacked a dozen other packages and they are all fine.

When installed together with @polkadot/api, causing `xxx has multiple versions, ensure that there is only one installed`

When installed together with @polkadot/api, there will be many errors:

@polkadot/metadata has multiple versions, ensure that there is only one installed.
Either remove and explicitly install matching versions or deupe using your package manager.
The following conflicting packages were found:
        4.2.1   /Users/will/Desktop/lt/node_modules/@polkadot/metadata
        4.2.1   /Users/will/Desktop/lt/node_modules/@substrate/txwrapper/node_modules/@polkadot/metadata
@polkadot/types-known has multiple versions, ensure that there is only one installed.
Either remove and explicitly install matching versions or deupe using your package manager.
The following conflicting packages were found:
        4.2.1   /Users/will/Desktop/lt/node_modules/@polkadot/types-known
        4.2.1   /Users/will/Desktop/lt/node_modules/@substrate/txwrapper/node_modules/@polkadot/types-known
@polkadot/types has multiple versions, ensure that there is only one installed.
Either remove and explicitly install matching versions or deupe using your package manager.
The following conflicting packages were found:
        4.2.1   /Users/will/Desktop/lt/node_modules/@polkadot/types
        4.2.1   /Users/will/Desktop/lt/node_modules/@substrate/txwrapper/node_modules/@polkadot/types
@polkadot/api has multiple versions, ensure that there is only one installed.
Either remove and explicitly install matching versions or deupe using your package manager.
The following conflicting packages were found:
        4.2.1   /Users/will/Desktop/lt/node_modules/@polkadot/api
        4.2.1   /Users/will/Desktop/lt/node_modules/@substrate/txwrapper/node_modules/@polkadot/api
@polkadot/api-derive has multiple versions, ensure that there is only one installed.
Either remove and explicitly install matching versions or deupe using your package manager.
The following conflicting packages were found:
        4.2.1   /Users/will/Desktop/lt/node_modules/@polkadot/api-derive
        4.2.1   /Users/will/Desktop/lt/node_modules/@substrate/txwrapper/node_modules/@polkadot/api-derive
@polkadot/rpc-core has multiple versions, ensure that there is only one installed.
Either remove and explicitly install matching versions or deupe using your package manager.
The following conflicting packages were found:
        4.2.1   /Users/will/Desktop/lt/node_modules/@polkadot/rpc-core
        4.2.1   /Users/will/Desktop/lt/node_modules/@substrate/txwrapper/node_modules/@polkadot/rpc-core
@polkadot/rpc-provider has multiple versions, ensure that there is only one installed.
Either remove and explicitly install matching versions or deupe using your package manager.
The following conflicting packages were found:
        4.2.1   /Users/will/Desktop/lt/node_modules/@polkadot/rpc-provider
        4.2.1   /Users/will/Desktop/lt/node_modules/@substrate/txwrapper/node_modules/@polkadot/rpc-provider

I definitely need @polkadot/api. But I also need @substrate/txwrapper's functionality to sign transactions offline, and broadcast it later. How do I solve these errors?

address Different

paritytech/txwrapper create address:
const mnemonic = mnemonicGenerate();
console.log(" memonic: ", mnemonic); // fringe history shy cupboard orbit supreme skin ladder soup shallow unaware wasp
console.log(keyring.createFromUri(mnemonic).address); // 5GgrbTa5op5Xkv1wY6PAVNFdCyS5BLPhErYLGGiywskBSV8K

use import polkadot{.js} extension The address generated by importing mnemonic words is: 5Gj1TdhEP1TSrcEYwUMUqFS8XwMUqgxDcMCGeW9pxXgyKfRS

why?

Add `staking.setPayee`

This would enable a user to (re-)set the payment target for a controller using txwrapper.

Getting an error when calling setKeys

Environment: [email protected]

const { importPrivateKey, session } = require('@substrate/txwrapper');

const metadataRpc = require('@polkadot/metadata/Metadata/v10/static');
const address = importPrivateKey('0xb58db8423c16f1cc6037125221aec3cc25e7943b5e805bfe43b172993eab475c').address;

const baseTxInfo = {
  address: 'HNZata7iMYWmk5RvZRTiAsSDhV8366zq2YGb3tLH5Upf74F', // seed "//Alice"
  blockHash:
    '0x1fc7493f3c1e9ac758a183839906475f8363aafb1b1d3e910fe16fab4ae1b582',
  blockNumber: 4302222,
  genesisHash:
    '0xe3777fa922cafbff200cadeaea1a76bd7898ad5b89f7848999058b50e715f636',
  metadataRpc,
  nonce: 1,
  specVersion: 1019,
  tip: 0,
  validityPeriod: 240 * 60
};

const newSessionKeys = '0xc789db36a43045f3a841f1e89f466196b987a6187dc723ec57b1d32957d927e038d7228cc027c07e5a87ff165c9f977b97578f10663f9b13ceb566ea96fa634a64ea351696ba1c8f7b8264c041c1b64ec1f5ab6b9c8b62acf94147d0ef31406c8a8bf532abebae1c03cb5731f0492f1b6cce91d827019f55b34ba868d9b8fc445cf5b6d3752b30643456c50b620eb46f21155809c5f8f550ee7ff1df0e50a355';

console.log(session.setKeys(newSessionKeys, baseTxInfo));

Output:

node index.js
/Users/anson/offline-tx/node_modules/@substrate/txwrapper/node_modules/@polkadot/types/known/index.js:45
  specName,
  ^

TypeError: Cannot destructure property `specName` of 'undefined' or 'null'.
    at Object.getSpecTypes (/Users/anson/offline-tx/node_modules/@substrate/txwrapper/node_modules/@polkadot/types/known/index.js:44:45)
    at Object.getRegistry (/Users/anson/offline-tx/node_modules/@substrate/txwrapper/lib/util/registry.js:21:31)
    at Object.createMethod (/Users/anson/offline-tx/node_modules/@substrate/txwrapper/lib/util/method.js:35:33)
    at Object.setKeys (/Users/anson/offline-tx/node_modules/@substrate/txwrapper/lib/methods/session/setKeys.js:11:19)
    at Object.<anonymous> (/Users/anson/offline-tx/index.js:22:21)
    at Module._compile (internal/modules/cjs/loader.js:868:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:879:10)
    at Module.load (internal/modules/cjs/loader.js:731:32)
    at Function.Module._load (internal/modules/cjs/loader.js:644:12)
    at Function.Module.runMain (internal/modules/cjs/loader.js:931:10)

Unable to run the example

Substrate build commit: * (HEAD detached at b36279559)

When running with yarn ts-node examples/index.ts

Result:

Expected Tx Hash: 0xe999eb06365d1d3721c14678797cec30f1f5e3b4746f344ab6a102034303f475
Error: Verification Error: Execution(ApiError("Could not convert parameter `tx` between node and runtime: No such variant in enum MultiSignature"))
    at /Users/anson/txwrapper/examples/index.ts:43:15
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
✨  Done in 6.33s.

In kusama transfer, the transaction is sent successfully, but the transaction cannot be seen in the block explorer

I send a tansfer in kusama with txwrapper, the transaction is sent successfully, but the transaction cannot be seen in the block explorer.
I use WsProvider

const provider = new WsProvider('wss://kusama-rpc.polkadot.io')

export function rpcToNode(method: string, params: any[] = []): Promise<any> { return provider.send(method, params); }

const actualTxHash = await rpcToNode('author_submitExtrinsic', [tx]);

Submit Extrinsic Error: createType(Extrinsic):: createType(ExtrinsicV4):: createType(ExtrinsicSignatureV4):: Unable to create Enum via index 207, in Ed25519, Sr25519, Ecdsa

I assembled the transaction body according to your example, but the broadcast failed and the error was reported.
createType(Extrinsic):: createType(ExtrinsicV4):: createType(ExtrinsicSignatureV4):: Unable to create Enum via index 207, in Ed25519, Sr25519, Ecdsa
The error message has always been this.
I asked the reason and it should be the type of registry. How do I reflect the type in the example, how do I need to modify it? This type of error is similar to Address and Account

here's my code, from the example, only the data is different

...
        const registry = getRegistry('Westend', 'Westend', specVersion, metadataRpc);
        registry.setMetadata(createMetadata(registry, metadataRpc));

        const unsigned = methods.balances.transfer(
            {
                value: 1,
                dest: '5GXvoYbSd2VZeabSY63mGdGJc6bDrmZg5mTz78ueEhKMAivm',
            },
            {
                address: '5FA5GKjtaCYHRhLtJ8bWhA1zP137PzTMmiDw8nfb5wDXSyGD',
                blockHash:blockHash.toHex(),
                blockNumber: registry
                    .createType('BlockNumber', block.header.number)
                    .toNumber(),
                eraPeriod: 64,
                genesisHash: genesisHash.toHex(),
                metadataRpc: metadataRpc,
                nonce, //
                specVersion,
                tip: 0,
                transactionVersion,
            },
            {
                metadataRpc,
                registry
            }
        );
        console.log('unsigned', unsigned);

       // registry.setMetadata(createMetadata(registry, metadataRpc));
        const signingPayload = createSigningPayload(unsigned, {metadataRpc, registry});
        console.log(`\nPayload to Sign: ${signingPayload}`);


        registry.setMetadata(createMetadata(registry, metadataRpc));
        const extrinsicPayload = registry.createType('ExtrinsicPayload', signingPayload, {version: TRANSACTION_VERSION});
        let sig = pair.sign(hex.hexToU8a(extrinsicPayload.toHex()));
        console.log('sig', u8a.u8aToHex(sig));

        let u8aHeader = new Uint8Array([0]);
        let u8aSig = u8a.u8aConcat(u8aHeader, sig);
        let Signature = u8a.u8aToHex(u8aSig);
        console.log('multi-Signature', Signature)

        registry.setMetadata(createMetadata(registry, metadataRpc));
        const tx = createSignedTx(unsigned, Signature, { metadataRpc, registry });
        console.log(`\nTransaction to Submit: ${tx}`);

        // Derive the tx hash of a signed transaction offline.
        const expectedTxHash = getTxHash(tx);
        console.log(`\nExpected Tx Hash: ${expectedTxHash}`);
...

Better docs for payoutNominator

#84 (comment)

This is a tuple that also needs the weight on each validator. Should check with @thiolliere about how to calculate this. I wouldn't block merging just for this comment, but if we do then let's also make an issue for better docs on payout_nominator.

Publicly release `3.1.3` & `3.1.4`

Hi!

Working on building some tooling that will utilize this paritytech/txwrapper and noticed that the latest few releases haven't been uploaded to the public registries. Any chance, you could release the latest versions or include this as part of your CI?

Thanks!

Parse large transfer values

When you try to enter a transfer value greater than 2^53-1, txwrapper fails with:

Error: createType(Call):: Struct: failed on 'args':: Struct: failed on 'value':: Assertion failed
    at createTypeUnsafe (/home/parity/projects/txintegration/node_modules/@substrate/txwrapper/node_modules/@polkadot/types/create/createType.js:68:11)
    at createType (/home/parity/projects/txintegration/node_modules/@substrate/txwrapper/node_modules/@polkadot/types/create/createType.js:80:10)
    at TypeRegistry.createType (/home/parity/projects/txintegration/node_modules/@substrate/txwrapper/node_modules/@polkadot/types/create/registry.js:187:39)
    at extrinsicFn (/home/parity/projects/txintegration/node_modules/@substrate/txwrapper/node_modules/@polkadot/metadata/Decorated/extrinsics/fromMetadata/createUnchecked.js:22:21)
    at Object.createMethod (/home/parity/projects/txintegration/node_modules/@substrate/txwrapper/lib/util/method.js:38:20)
    at Object.transferKeepAlive (/home/parity/projects/txintegration/node_modules/@substrate/txwrapper/lib/methods/balances/transferKeepAlive.js:10:19)
    at Object.<anonymous> (/home/parity/projects/txintegration/construction.ts:110:36)
    at step (/home/parity/projects/txintegration/construction.ts:33:23)
    at Object.next (/home/parity/projects/txintegration/construction.ts:14:53)
    at fulfilled (/home/parity/projects/txintegration/construction.ts:5:58)
error Command failed with exit code 1.

Example fails (on parsing balance type?)

@Jam10o when i run ./node_modules/.bin/ts-node examples/index.ts to test txwrapper,it tips me:

SS58-Encoded Address: 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY
Error: createType(Call):: Struct: failed on 'args':: Balance: Input too large. Found input with 246 bits, expected 128
    at createTypeUnsafe (/Users/Zhangyabo/Develop/WebStormWorkspace/txwrapper/node_modules/@polkadot/types/create/createType.js:68:11)
    at createType (/Users/Zhangyabo/Develop/WebStormWorkspace/txwrapper/node_modules/@polkadot/types/create/createType.js:80:10)
    at TypeRegistry.createType (/Users/Zhangyabo/Develop/WebStormWorkspace/txwrapper/node_modules/@polkadot/types/create/registry.js:187:39)
    at Object.decodeUnsignedTx (/Users/Zhangyabo/Develop/WebStormWorkspace/txwrapper/src/decode/decodeUnsignedTx.ts:58:31)
    at Object.decode (/Users/Zhangyabo/Develop/WebStormWorkspace/txwrapper/src/decode/decode.ts:101:10)
    at /Users/Zhangyabo/Develop/WebStormWorkspace/txwrapper/examples/index.ts:122:27
    at Generator.next (<anonymous>)
    at fulfilled (/Users/Zhangyabo/Develop/WebStormWorkspace/txwrapper/examples/index.ts:5:58)
    at process._tickCallback (internal/process/next_tick.js:68:7)

according to the user they have not changed the example other than the rpc endpoint.

Signature can't broadcast at polkadot.js.org/app

When I broadcast a signature built by txwrapper, I got an error below
submitExtrinsic(extrinsic: Extrinsic): Hash:: 1010: Invalid Transaction: BadProof

I had tried changing the genesisHash to 0xb0a8d493285c2df73290dfb7e61f870f17b41801197a149ca93654499ea3dafe
and the specVersion to 1045,
and the method callIndex from 0603 to 0400. but nothing changed, the error is always the same.

Could someone give me some suggestions?

Add Staking Payout Functions

Once paritytech/substrate#4474 gets merged, add:

  • staking.payoutNominator
  • staking.payoutValidator

Note: These functions are quite dangerous and the wrong input parameters can cause loss of funds. Make sure that the documentation is clear and precise.

Submit Extrinsic: Bad Proof

The signature is a 65-bit signature in multi-sign format, the last 64 bits at https://polkadot.js.org/apps/#/ Toolbox/sign verification here is correct, do not know which parameters are wrong, thanks for the help

here's my code, from the example, only the data is different

...
        const unsigned = methods.balances.transfer(
            {
                value: 1,
                dest: to,
            },
            {
                address: from,
                 blockHash: blockHash.toHex(),
                 blockNumber: registry.createType('BlockNumber', block.header.number).toNumber(),
                 eraPeriod:64,
                genesisHash: genesisHash.toHex(),
                metadataRpc: metadataRpc,
                nonce, 
                specVersion,
                tip: 0,
                transactionVersion
            },
            {
                metadataRpc,
                registry
            }
        );
        console.log('unsigned', unsigned);

        const signingPayload = createSigningPayload(unsigned, {metadataRpc, registry});

        const extrinsicPayload = registry.createType('ExtrinsicPayload', signingPayload, {version: TRANSACTION_VERSION});
        let sig = pair.sign(hex.hexToU8a(extrinsicPayload.toHex()), {withType: true});

        const tx = createSignedTx(unsigned, sig, { metadataRpc, registry });
        console.log(`\nTransaction to Submit: ${tx}`);
...

Let CI generate docs

On each push to master, CI should run yarn docs and commit back to master.

Having doc changes on each PR makes PRs difficult to read

Filter out error message from `decode` when decoding a signed tx

In decode we first try to decode as a signing payload, and if that fails we assume it needs to be decoded as a signed TX. With recent updates to polkadot-js error messages this results in the following being logged while decode is executing successful on signed TX:

2020-11-25 22:19:10        REGISTRY: Error: findMetaCall: Unable to find Call with index 0x84d4/[132,212]
    at assert (/Users/zeke/Documents/parity/txwrapper-core/node_modules/@polkadot/util/assert.js:34:11)
    at assertReturn (/Users/zeke/Documents/parity/txwrapper-core/node_modules/@polkadot/util/assert.js:44:3)
    at TypeRegistry.findMetaCall (/Users/zeke/Documents/parity/txwrapper-core/node_modules/@polkadot/types/create/registry.js:263:35)
    at decodeCallViaU8a (/Users/zeke/Documents/parity/txwrapper-core/node_modules/@polkadot/types/generic/Call.js:72:34)
    at decodeCall (/Users/zeke/Documents/parity/txwrapper-core/node_modules/@polkadot/types/generic/Call.js:96:12)
    at new GenericCall (/Users/zeke/Documents/parity/txwrapper-core/node_modules/@polkadot/types/generic/Call.js:127:21)
    at new Type (/Users/zeke/Documents/parity/txwrapper-core/node_modules/@polkadot/types/create/registry.js:300:16)
    at initType (/Users/zeke/Documents/parity/txwrapper-core/node_modules/@polkadot/types/create/createType.js:49:19)
    at createTypeUnsafe (/Users/zeke/Documents/parity/txwrapper-core/node_modules/@polkadot/types/create/createType.js:68:12)
    at createType (/Users/zeke/Documents/parity/txwrapper-core/node_modules/@polkadot/types/create/createType.js:83:10)

With this recently merged PR: https://github.com/polkadot-js/api/pull/2952/files we should be able to use createTypeUnsafe, passing in { withoutLog: true } to silence the warning.

Add pallet methods for Polkadot & Kusama PLOs

With Parachain Lease Offerings (PLOs) on the horizon the necessary pallet methods should be added to txwrapper to facilitate participation.

The Parachain onboarding process (crowdloan, auctions, registration, etc .. ) can be played using the Westend runtime on Polkadot master. The command to run should be

polkadot --chain=westend-dev --alice

N.B. This should be the last set of pallet methods added to txwrapper. In the future txwrapper users should migrate to txwrapper-polkadot

Methods:

  • contribute
  • withdraw

Error: 1010 Invalid Transaction: "Transaction is outdated"

I have cloned txwrapper repo and I'm trying to run the polkadot.ts file w.r.t the commands given in the example folder. As far now, I have setup my westend node, got my westend tokens from the faucet and I have added to it to the account derived from the code, but when I try to run the code it keeps on showing Error: 1010 Invalid Transaction: "Transaction is outdated" after the expected txHash has been developed, but when it comes to actual tx it fails. Can anyone please help me on this issue?

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.