@polkadot/types#TypeRegistry TypeScript Examples

The following examples show how to use @polkadot/types#TypeRegistry. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: utils.ts    From gear-js with GNU General Public License v3.0 7 votes vote down vote up
export function getTypesFromTypeDef(
  types: Uint8Array | Hex,
  registry?: Registry,
): { typesFromTypeDef: any; namespaces: Map<string, string> } {
  if (!registry) {
    registry = new TypeRegistry();
  }
  const typesFromTypeDef = {};
  const namespaces = new Map<string, string>();
  const portableReg = new PortableRegistry(registry, isHex(types) ? hexToU8a(types) : types, true);
  portableReg.types.forEach(({ id, type: { path } }) => {
    const typeDef = portableReg.getTypeDef(id);
    if (path.length === 0 || (!typeDef.lookupName && !typeDef.lookupNameRoot)) {
      return;
    }
    const name = portableReg.getName(id);
    let camelCasedNamespace = toCamelCase(path.slice(0, path.length - 1));
    if (camelCasedNamespace === name) {
      camelCasedNamespace = path.length > 2 ? toCamelCase(path.slice(0, path.length - 2)) : undefined;
    }
    namespaces.set(name.replace(camelCasedNamespace, ''), name);
    typesFromTypeDef[typeDef.lookupName || typeDef.lookupNameRoot] = typeDef.type.toString();
  });
  return { typesFromTypeDef, namespaces };
}
Example #2
Source File: faucet.ts    From interbtc-api with Apache License 2.0 6 votes vote down vote up
constructor(private api: ApiPromise, url: string) {
        super(url);
        this.registry = new TypeRegistry();
        this.registry.register(getAPITypes());

        this.constr = {
            FundAccountJsonRpcRequest: this.registry.createClass("FundAccountJsonRpcRequest"),
        };
    }
Example #3
Source File: electrs.ts    From interbtc-api with Apache License 2.0 6 votes vote down vote up
async getParsedExecutionParameters(txid: string): Promise<[Bytes, Bytes]> {
        const [unparsedMerkleProof, unparsedRawTx] = await Promise.all([
            this.getMerkleProof(txid),
            this.getRawTransaction(txid),
        ]);
        // To avoid taking an ApiPromise object as a constructor parameter,
        // use the default TypeRegistry (without custom type metadata),
        // because the Bytes type instantiated is provided by default.
        const registry = new TypeRegistry();

        const merkleProof = registry.createType("Bytes", "0x" + unparsedMerkleProof);
        const rawTx = registry.createType("Bytes", "0x" + unparsedRawTx);
        return [merkleProof, rawTx];
    }
Example #4
Source File: keyring.ts    From sdk with Apache License 2.0 6 votes vote down vote up
/**
 * sign tx from dapp as extension
 */
async function signTxAsExtension(password: string, json: any) {
  return new Promise((resolve) => {
    const keyPair = keyring.getPair(json["address"]);
    try {
      if (!keyPair.isLocked) {
        keyPair.lock();
      }
      keyPair.decodePkcs8(password);

      let registry: any;
      if (!(<any>window).api) {
        registry = new TypeRegistry();
        registry.setMetadata(new Metadata(registry, metaDataMap["kusama"]));
      } else {
        registry = (<any>window).api.registry;
      }

      registry.setSignedExtensions(json["signedExtensions"]);
      const payload = registry.createType("ExtrinsicPayload", json, {
        version: json["version"],
      });
      const signed = payload.sign(keyPair);
      resolve(signed);
    } catch (err) {
      resolve({ error: err.message });
    }
  });
}
Example #5
Source File: bitcoin.ts    From interbtc-api with Apache License 2.0 6 votes vote down vote up
export function btcAddressFromParams(
    registry: TypeRegistry,
    params: { p2pkh: H160 | string } | { p2sh: H160 | string } | { p2wpkhv0: H160 | string }
): BitcoinAddress {
    registry.register;
    return registry.createType<BitcoinAddress>("BitcoinAddress", {
        ...params,
    });
}
Example #6
Source File: bitcoin.test.ts    From interbtc-api with Apache License 2.0 6 votes vote down vote up
describe("Bitcoin", () => {
    let registry: TypeRegistry;

    before(() => {
        registry = createAPIRegistry();
    });

    it("should get correct hash for address", () => {
        // compare hex because type lib has trouble with this enum
        assert.deepEqual(decodeBtcAddress("bcrt1qjvmc5dtm4qxgtug8faa5jdedlyq4v76ngpqgrl", bitcoinjs.networks.regtest), {
            p2wpkhv0: "0x93378a357ba80c85f1074f7b49372df901567b53",
        });
        assert.deepEqual(decodeBtcAddress("tb1q45uq0q4v22fspeg3xjnkgf8a0v7pqgjks4k6sz", bitcoinjs.networks.testnet), {
            p2wpkhv0: "0xad380782ac529300e51134a76424fd7b3c102256",
        });
        assert.deepEqual(decodeBtcAddress("bc1qar0srrr7xfkvy5l643lydnw9re59gtzzwf5mdq", bitcoinjs.networks.bitcoin), {
            p2wpkhv0: "0xe8df018c7e326cc253faac7e46cdc51e68542c42",
        });
    });
});
Example #7
Source File: keyring.ts    From sdk with Apache License 2.0 6 votes vote down vote up
/**
 * sign tx with QR
 */
async function signAsync(chain: string, password: string) {
  return new Promise((resolve) => {
    const { unsignedData } = getSigner();
    const keyPair = keyring.getPair(unsignedData.data.account);
    try {
      if (!keyPair.isLocked) {
        keyPair.lock();
      }
      keyPair.decodePkcs8(password);

      let payload: any;
      if (!(<any>window).api) {
        const registry = new TypeRegistry();
        registry.setMetadata(new Metadata(registry, metaDataMap[chain]));
        payload = registry.createType("ExtrinsicPayload", unsignedData.data.data, {
          version: 4,
        });
      } else {
        payload = (<any>window).api.registry.createType("ExtrinsicPayload", unsignedData.data.data, {
          version: (<any>window).api.extrinsicVersion,
        });
      }

      const signed = payload.sign(keyPair);
      resolve(signed);
    } catch (err) {
      resolve({ error: err.message });
    }
  });
}
Example #8
Source File: helpers.spec.ts    From guardian with Apache License 2.0 6 votes vote down vote up
describe('substrate helpers', () => {
  const registry = new TypeRegistry();
  const event = registry.createType('Event');
  event.set('data', {
    meta: {
      docs: ['hello world', 'Transfer amount. \\[sender, receiver, amount\\]']
    }
  } as any);

  it('getEventParams', () => {
    const params = getEventParams(event);
    expect(params).toStrictEqual(['sender', 'receiver', 'amount']);
  });

  it('getEventParams fallback', () => {
    event.set('data', {
      meta: {
        docs: ['Transfer amount. [sender, receiver, amount]']
      }
    } as any);
    const params = getEventParams(event);
    expect(params).toStrictEqual(['sender', 'receiver', 'amount']);
  });

  it('getEventParams from fields', () => {
    event.set('data', {
      meta: {
        fields: [
          registry.createType('Si1Field', { name: 'sender' }),
          registry.createType('Si1Field', { name: 'receiver' }),
          registry.createType('Si1Field', { name: 'amount' })
        ],
        docs: ['Transfer amount.']
      }
    } as any);
    const params = getEventParams(event);
    expect(params).toStrictEqual(['sender', 'receiver', 'amount']);
  });
});
Example #9
Source File: encoding.test.ts    From interbtc-api with Apache License 2.0 5 votes vote down vote up
describe("Encoding", () => {
    let registry: TypeRegistry;

    const createH256Le = (hash: string): H256Le => {
        return new (registry.createClass("H256Le"))(registry, hash) as H256Le;
    };

    before(() => {
        registry = new TypeRegistry();
        registry.register(getAPITypes());
    });

    it("should encode / decode same block hash as H256Le", () => {
        const blockHashHexLE = "0x9067166e896765258f6636a082abad6953f17a0e8dc21fc4f85648ceeedbda69";
        const blockHash = createH256Le(blockHashHexLE);
        return assert.equal(blockHash.toHex(), blockHashHexLE);
    });

    it("should strip prefix", () => {
        const blockHashHexBEWithPrefix = "0x5499ac3ca3ddf563ace6b6a56ec2e8bdc5f796bef249445c36d90a69d0757d4c";
        const blockHashHexBEWithoutPrefix = "5499ac3ca3ddf563ace6b6a56ec2e8bdc5f796bef249445c36d90a69d0757d4c";
        assert.equal(stripHexPrefix(blockHashHexBEWithPrefix), blockHashHexBEWithoutPrefix);
        assert.equal(stripHexPrefix(blockHashHexBEWithoutPrefix), blockHashHexBEWithoutPrefix);
    });

    it("should reverse endianness from le to be", () => {
        const blockHashHexLE = "0x9067166e896765258f6636a082abad6953f17a0e8dc21fc4f85648ceeedbda69";
        const blockHashHexBE = "0x69dadbeece4856f8c41fc28d0e7af15369adab82a036668f256567896e166790";
        const blockHash = createH256Le(blockHashHexLE);

        const result = uint8ArrayToString(reverseEndianness(blockHash));
        return assert.equal(result, stripHexPrefix(blockHashHexBE));
    });

    it("should reverse endianness hex", () => {
        const blockHashHexLE = "0x9067166e896765258f6636a082abad6953f17a0e8dc21fc4f85648ceeedbda69";
        const blockHashHexBE = "0x69dadbeece4856f8c41fc28d0e7af15369adab82a036668f256567896e166790";
        return assert.equal(reverseEndiannessHex(blockHashHexLE), stripHexPrefix(blockHashHexBE));
    });
});
Example #10
Source File: address.ts    From subscan-multisig-react with Apache License 2.0 5 votes vote down vote up
registry = new TypeRegistry()
Example #11
Source File: Args.tsx    From subscan-multisig-react with Apache License 2.0 5 votes vote down vote up
// eslint-disable-next-line complexity
function formatAddressValue(value: string | string[], chain: Chain) {
  const encodeAddr = (addr: string) => {
    try {
      // eslint-disable-next-line no-magic-numbers
      const formatVal = addr.padStart(66, '0x');

      return encodeAddress(formatVal, +chain.ss58Format);
    } catch (err) {
      console.error('? ~ file: Args.tsx ~ line 57 ~ formatAddressValue ~ err', err);

      return addr;
    }
  };

  if (isString(value)) {
    // eslint-disable-next-line no-magic-numbers
    if (value.length < 12 && /^\d+$/.test(value)) {
      const registry = new TypeRegistry();

      registry.setChainProperties(
        registry.createType('ChainProperties', { ss58Format: +chain.ss58Format }) as ChainProperties
      );

      const ss58 = registry.createType('AccountIndex', +value).toString();

      return <SubscanLink address={ss58} copyable />;
    }
    // eslint-disable-next-line no-magic-numbers
    if (value.length > 60) {
      return <SubscanLink address={encodeAddr(value)} copyable />;
    }

    return <SubscanLink address={value} copyable />;
  }

  if (isArray(value)) {
    return (
      <>
        {value.map((item: string) => (
          <SubscanLink address={encodeAddr(item)} copyable key={item} />
        ))}
      </>
    );
  }

  return null;
}
Example #12
Source File: useApiConnection.ts    From parity-bridges-ui with GNU General Public License v3.0 5 votes vote down vote up
registry = new TypeRegistry()
Example #13
Source File: testHelpers.ts    From guardian with Apache License 2.0 5 votes vote down vote up
registry = new TypeRegistry()
Example #14
Source File: testHelpers.ts    From guardian with Apache License 2.0 5 votes vote down vote up
registry = new TypeRegistry()
Example #15
Source File: mockApiPromise.ts    From guardian with Apache License 2.0 5 votes vote down vote up
registry = new TypeRegistry()
Example #16
Source File: registry.ts    From subsocial-js with GNU General Public License v3.0 5 votes vote down vote up
registry = new TypeRegistry()
Example #17
Source File: factory.ts    From interbtc-api with Apache License 2.0 5 votes vote down vote up
export function createAPIRegistry(): TypeRegistry {
    const registry = new TypeRegistry();
    registry.register(getAPITypes());
    return registry;
}
Example #18
Source File: faucet.ts    From interbtc-api with Apache License 2.0 5 votes vote down vote up
registry: TypeRegistry;
Example #19
Source File: CreateType.ts    From gear-js with GNU General Public License v3.0 5 votes vote down vote up
constructor(gearApi?: GearApi) {
    this.registry = gearApi?.registry || new TypeRegistry();
    this.namespaces = undefined;
  }