@polkadot/util#bnToHex TypeScript Examples

The following examples show how to use @polkadot/util#bnToHex. 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: storage.ts    From interbtc-api with Apache License 2.0 6 votes vote down vote up
export async function setNumericStorage(
    api: ApiPromise,
    moduleName: string,
    storageItemName: string,
    value: BN,
    account: AddressOrPair,
    bits = 32,
    isLittleEndian = true
): Promise<void> {
    const data = bnToHex(value, bits, isLittleEndian);
    await setStorage(api, moduleName, storageItemName, data, account);
}
Example #2
Source File: test-asset-manager.ts    From moonbeam with GNU General Public License v3.0 5 votes vote down vote up
describeDevMoonbeam("XCM - asset manager - Remove asset from supported", (context) => {
  let assetId: string;
  let alith: KeyringPair;
  before("should be able to change existing asset type", async function () {
    const keyringEth = new Keyring({ type: "ethereum" });
    alith = keyringEth.addFromUri(ALITH_PRIV_KEY, null, "ethereum");

    const parachainOne = context.polkadotApi;
    // registerForeignAsset
    const { events: eventsRegister } = await createBlockWithExtrinsic(
      context,
      alith,
      parachainOne.tx.sudo.sudo(
        parachainOne.tx.assetManager.registerForeignAsset(
          sourceLocation,
          assetMetadata,
          new BN(1),
          true
        )
      )
    );

    eventsRegister.forEach((e) => {
      if (e.section.toString() === "assetManager") {
        assetId = e.data[0].toHex();
      }
    });
    assetId = assetId.replace(/,/g, "");

    // setAssetUnitsPerSecond
    const { events } = await createBlockWithExtrinsic(
      context,
      alith,
      parachainOne.tx.sudo.sudo(
        parachainOne.tx.assetManager.setAssetUnitsPerSecond(sourceLocation, 1, 0)
      )
    );
    expect(events[1].method.toString()).to.eq("UnitsPerSecondChanged");
    expect(events[4].method.toString()).to.eq("ExtrinsicSuccess");

    // check asset in storage
    const registeredAsset = ((await parachainOne.query.assets.asset(assetId)) as any).unwrap();
    expect(registeredAsset.owner.toString()).to.eq(palletId);

    await verifyLatestBlockFees(context, expect);
  });

  it("should remove an asset from our supported fee payments", async function () {
    // ChangeAssetType
    await createBlockWithExtrinsic(
      context,
      alith,
      context.polkadotApi.tx.sudo.sudo(
        context.polkadotApi.tx.assetManager.removeSupportedAsset(sourceLocation, 1)
      )
    );

    // assetId
    let id = (
      (await context.polkadotApi.query.assetManager.assetTypeId(sourceLocation)) as any
    ).unwrap();

    // asset units per second removed
    let assetUnitsPerSecond = (await context.polkadotApi.query.assetManager.assetTypeUnitsPerSecond(
      sourceLocation
    )) as any;

    // Supported assets should be 0
    let supportedAssets =
      (await context.polkadotApi.query.assetManager.supportedFeePaymentAssets()) as any;

    expect(assetUnitsPerSecond.isNone).to.eq(true);
    expect(bnToHex(id)).to.eq(assetId);
    // the asset should not be supported
    expect(supportedAssets.length).to.eq(0);
  });
});
Example #3
Source File: parachain.ts    From polkadot-launch with MIT License 5 votes vote down vote up
export function parachainAccount(id: string) {
	let prefix = stringToHex("para");
	let encoded_id = bnToHex(parseInt(id), { isLe: true });
	let address_bytes = (prefix + hexStripPrefix(encoded_id)).padEnd(64 + 2, "0");
	let address = encodeAddress(address_bytes);

	return address;
}
Example #4
Source File: test-asset-manager.ts    From moonbeam with GNU General Public License v3.0 4 votes vote down vote up
describeDevMoonbeam("XCM - asset manager - Change existing asset", (context) => {
  let assetId: string;
  let alith: KeyringPair;
  before("should be able to change existing asset type", async function () {
    const keyringEth = new Keyring({ type: "ethereum" });
    alith = keyringEth.addFromUri(ALITH_PRIV_KEY, null, "ethereum");

    const parachainOne = context.polkadotApi;
    // registerForeignAsset
    const { events: eventsRegister } = await createBlockWithExtrinsic(
      context,
      alith,
      parachainOne.tx.sudo.sudo(
        parachainOne.tx.assetManager.registerForeignAsset(
          sourceLocation,
          assetMetadata,
          new BN(1),
          true
        )
      )
    );

    eventsRegister.forEach((e) => {
      if (e.section.toString() === "assetManager") {
        assetId = e.data[0].toHex();
      }
    });
    assetId = assetId.replace(/,/g, "");

    // setAssetUnitsPerSecond
    const { events } = await createBlockWithExtrinsic(
      context,
      alith,
      parachainOne.tx.sudo.sudo(
        parachainOne.tx.assetManager.setAssetUnitsPerSecond(sourceLocation, 1, 0)
      )
    );
    expect(events[1].method.toString()).to.eq("UnitsPerSecondChanged");
    expect(events[4].method.toString()).to.eq("ExtrinsicSuccess");

    // check asset in storage
    const registeredAsset = ((await parachainOne.query.assets.asset(assetId)) as any).unwrap();
    expect(registeredAsset.owner.toString()).to.eq(palletId);

    await verifyLatestBlockFees(context, expect);
  });

  it("should change the asset Id", async function () {
    // ChangeAssetType
    await createBlockWithExtrinsic(
      context,
      alith,
      context.polkadotApi.tx.sudo.sudo(
        context.polkadotApi.tx.assetManager.changeExistingAssetType(assetId, newSourceLocation, 1)
      )
    );

    // asset_type
    let assetType = (await context.polkadotApi.query.assetManager.assetIdType(assetId)) as Object;

    // assetId
    let id = (
      (await context.polkadotApi.query.assetManager.assetTypeId(newSourceLocation)) as any
    ).unwrap();

    // asset units per second changed
    let assetUnitsPerSecond = (
      (await context.polkadotApi.query.assetManager.assetTypeUnitsPerSecond(
        newSourceLocation
      )) as any
    ).unwrap();

    // Supported assets
    let supportedAssets =
      (await context.polkadotApi.query.assetManager.supportedFeePaymentAssets()) as any;

    expect(assetUnitsPerSecond.toString()).to.eq(new BN(1).toString());
    expect(assetType.toString()).to.eq(JSON.stringify(newSourceLocation).toLowerCase());
    expect(bnToHex(id)).to.eq(assetId);
    expect(supportedAssets[0].toString()).to.eq(JSON.stringify(newSourceLocation).toLowerCase());
  });
});
Example #5
Source File: test-precompile-assets-erc20.ts    From moonbeam with GNU General Public License v3.0 4 votes vote down vote up
describeDevMoonbeamAllEthTxTypes(
  "Precompiles - Assets-ERC20 Wasm",
  (context) => {
    let sudoAccount, assetId, iFace;
    before("Setup contract and mock balance", async () => {
      const keyring = new Keyring({ type: "ethereum" });
      sudoAccount = await keyring.addFromUri(ALITH_PRIV_KEY, null, "ethereum");
      // We need to mint units with sudo.setStorage, as we dont have xcm mocker yet
      // And we need relay tokens for issuing a transaction to be executed in the relay
      const balance = new BN("100000000000000");
      const assetBalance = context.polkadotApi.createType("PalletAssetsAssetAccount", {
        balance: balance,
      });
      assetId = context.polkadotApi.createType(
        "u128",
        new BN("42259045809535163221576417993425387648")
      );

      const assetDetails = context.polkadotApi.createType("PalletAssetsAssetDetails", {
        supply: balance,
      });

      await mockAssetBalance(context, assetBalance, assetDetails, sudoAccount, assetId, ALITH);

      let beforeAssetBalance = (
        (await context.polkadotApi.query.assets.account(assetId, ALITH)) as any
      ).balance as BN;

      const contractData = await getCompiled("ERC20Instance");
      iFace = new ethers.utils.Interface(contractData.contract.abi);
      const { contract, rawTx } = await createContract(context, "ERC20Instance");
      const address = contract.options.address;
      await context.createBlock({ transactions: [rawTx] });
    });

    it("allows to call name", async function () {
      let data = iFace.encodeFunctionData(
        // action
        "name",
        []
      );

      const tx_call = await customWeb3Request(context.web3, "eth_call", [
        {
          from: GENESIS_ACCOUNT,
          value: "0x0",
          gas: "0x10000",
          gasPrice: GAS_PRICE,
          to: ADDRESS_ERC20,
          data: data,
        },
      ]);

      let expected = stringToHex("DOT");
      let offset = numberToHex(32).slice(2).padStart(64, "0");
      let length = numberToHex(3).slice(2).padStart(64, "0");
      // Bytes are padded at the end
      let expected_hex = expected.slice(2).padEnd(64, "0");
      expect(tx_call.result).equals("0x" + offset + length + expected_hex);
    });

    it("allows to call symbol", async function () {
      let data = iFace.encodeFunctionData(
        // action
        "symbol",
        []
      );

      const tx_call = await customWeb3Request(context.web3, "eth_call", [
        {
          from: GENESIS_ACCOUNT,
          value: "0x0",
          gas: "0x10000",
          gasPrice: GAS_PRICE,
          to: ADDRESS_ERC20,
          data: data,
        },
      ]);

      let expected = stringToHex("DOT");
      let offset = numberToHex(32).slice(2).padStart(64, "0");
      let length = numberToHex(3).slice(2).padStart(64, "0");
      // Bytes are padded at the end
      let expected_hex = expected.slice(2).padEnd(64, "0");
      expect(tx_call.result).equals("0x" + offset + length + expected_hex);
    });

    it("allows to call decimals", async function () {
      let data = iFace.encodeFunctionData(
        // action
        "decimals",
        []
      );

      const tx_call = await customWeb3Request(context.web3, "eth_call", [
        {
          from: GENESIS_ACCOUNT,
          value: "0x0",
          gas: "0x10000",
          gasPrice: GAS_PRICE,
          to: ADDRESS_ERC20,
          data: data,
        },
      ]);

      let expected = "0x" + numberToHex(12).slice(2).padStart(64, "0");
      expect(tx_call.result).equals(expected);
    });

    it("allows to call getBalance", async function () {
      let data = iFace.encodeFunctionData(
        // action
        "balanceOf",
        [ALITH]
      );

      const tx_call = await customWeb3Request(context.web3, "eth_call", [
        {
          from: GENESIS_ACCOUNT,
          value: "0x0",
          gas: "0x10000",
          gasPrice: GAS_PRICE,
          to: ADDRESS_ERC20,
          data: data,
        },
      ]);
      let amount = new BN(100000000000000);

      let amount_hex = "0x" + bnToHex(amount).slice(2).padStart(64, "0");
      expect(tx_call.result).equals(amount_hex);
    });

    it("allows to call totalSupply", async function () {
      let data = iFace.encodeFunctionData(
        // action
        "totalSupply",
        []
      );
      const tx_call = await customWeb3Request(context.web3, "eth_call", [
        {
          from: GENESIS_ACCOUNT,
          value: "0x0",
          gas: "0x10000",
          gasPrice: GAS_PRICE,
          to: ADDRESS_ERC20,
          data: data,
        },
      ]);

      let amount = new BN(100000000000000);

      let amount_hex = "0x" + bnToHex(amount).slice(2).padStart(64, "0");
      expect(tx_call.result).equals(amount_hex);
    });
  },
  true
);
Example #6
Source File: test-precompile-assets-erc20.ts    From moonbeam with GNU General Public License v3.0 4 votes vote down vote up
describeDevMoonbeamAllEthTxTypes(
  "Precompiles - Assets-ERC20 Wasm",
  (context) => {
    let sudoAccount, assetId, iFace;
    before("Setup contract and mock balance", async () => {
      const keyring = new Keyring({ type: "ethereum" });
      sudoAccount = await keyring.addFromUri(ALITH_PRIV_KEY, null, "ethereum");
      // We need to mint units with sudo.setStorage, as we dont have xcm mocker yet
      // And we need relay tokens for issuing a transaction to be executed in the relay
      const balance = context.polkadotApi.createType("Balance", 100000000000000);
      const assetBalance = context.polkadotApi.createType("PalletAssetsAssetAccount", {
        balance: balance,
      });

      assetId = context.polkadotApi.createType(
        "u128",
        new BN("42259045809535163221576417993425387648")
      );
      const assetDetails = context.polkadotApi.createType("PalletAssetsAssetDetails", {
        supply: balance,
      });

      await mockAssetBalance(context, assetBalance, assetDetails, sudoAccount, assetId, ALITH);

      const contractData = await getCompiled("ERC20Instance");
      iFace = new ethers.utils.Interface(contractData.contract.abi);
      const { rawTx } = await createContract(context, "ERC20Instance");
      await context.createBlock({ transactions: [rawTx] });
    });
    it("allows to approve transfers, and allowance matches", async function () {
      let data = iFace.encodeFunctionData(
        // action
        "approve",
        [BALTATHAR, 1000]
      );

      const tx = await createTransaction(context, {
        from: ALITH,
        privateKey: ALITH_PRIV_KEY,
        value: "0x0",
        gas: "0x200000",
        gasPrice: GAS_PRICE,
        to: ADDRESS_ERC20,
        data: data,
      });

      const block = await context.createBlock({
        transactions: [tx],
      });

      const receipt = await context.web3.eth.getTransactionReceipt(block.txResults[0].result);

      expect(receipt.status).to.equal(true);
      expect(receipt.logs.length).to.eq(1);
      expect(receipt.logs[0].address).to.eq(ADDRESS_ERC20);
      expect(receipt.logs[0].topics.length).to.eq(3);
      expect(receipt.logs[0].topics[0]).to.eq(SELECTORS.logApprove);
      let approvals = (await context.polkadotApi.query.assets.approvals(
        assetId,
        ALITH,
        BALTATHAR
      )) as any;

      expect(approvals.unwrap().amount.eq(new BN(1000))).to.equal(true);
    });
    it("should gather the allowance", async function () {
      let data = iFace.encodeFunctionData(
        // action
        "allowance",
        [ALITH, BALTATHAR]
      );

      const tx_call = await customWeb3Request(context.web3, "eth_call", [
        {
          from: GENESIS_ACCOUNT,
          value: "0x0",
          gas: "0x10000",
          gasPrice: GAS_PRICE,
          to: ADDRESS_ERC20,
          data: data,
        },
      ]);
      let amount = new BN(1000);

      let amount_hex = "0x" + bnToHex(amount).slice(2).padStart(64, "0");
      expect(tx_call.result).equals(amount_hex);
    });
  },
  true
);
Example #7
Source File: test-precompile-local-assets-erc20.ts    From moonbeam with GNU General Public License v3.0 4 votes vote down vote up
describeDevMoonbeamAllEthTxTypes(
  "Precompiles - Assets-ERC20 Wasm",
  (context) => {
    let sudoAccount, baltatharAccount, assetId, iFace, assetAddress, contractInstanceAddress;
    before("Setup contract and mock balance", async () => {
      const keyring = new Keyring({ type: "ethereum" });
      sudoAccount = await keyring.addFromUri(ALITH_PRIV_KEY, null, "ethereum");
      baltatharAccount = await keyring.addFromUri(BALTATHAR_PRIV_KEY, null, "ethereum");

      // registerAsset
      const { events: eventsRegister } = await createBlockWithExtrinsic(
        context,
        sudoAccount,
        context.polkadotApi.tx.sudo.sudo(
          context.polkadotApi.tx.assetManager.registerLocalAsset(
            baltatharAccount.address,
            baltatharAccount.address,
            true,
            new BN(1)
          )
        )
      );

      // Look for assetId in events
      eventsRegister.forEach((e) => {
        if (e.section.toString() === "assetManager") {
          assetId = e.data[0].toHex();
        }
      });
      assetId = assetId.replace(/,/g, "");

      // Set metadata
      await createBlockWithExtrinsic(
        context,
        baltatharAccount,
        context.polkadotApi.tx.localAssets.setMetadata(assetId, "Local", "Local", new BN(12))
      );

      // mint asset
      await createBlockWithExtrinsic(
        context,
        baltatharAccount,
        context.polkadotApi.tx.localAssets.mint(assetId, baltatharAccount.address, 100000000000000)
      );

      assetAddress = u8aToHex(new Uint8Array([...hexToU8a("0xFFFFFFFE"), ...hexToU8a(assetId)]));

      const contractData = await getCompiled("LocalAssetExtendedErc20Instance");
      iFace = new ethers.utils.Interface(contractData.contract.abi);
      const { contract, rawTx } = await createContract(context, "LocalAssetExtendedErc20Instance");
      contractInstanceAddress = contract.options.address;
      await context.createBlock({ transactions: [rawTx] });
    });

    it("allows to call name", async function () {
      let data = iFace.encodeFunctionData(
        // action
        "name",
        []
      );

      const tx_call = await customWeb3Request(context.web3, "eth_call", [
        {
          from: ALITH,
          value: "0x0",
          gas: "0x10000",
          gasPrice: GAS_PRICE,
          to: assetAddress,
          data: data,
        },
      ]);

      let expected = stringToHex("Local");
      let offset = numberToHex(32).slice(2).padStart(64, "0");
      let length = numberToHex(5).slice(2).padStart(64, "0");
      // Bytes are padded at the end
      let expected_hex = expected.slice(2).padEnd(64, "0");
      expect(tx_call.result).equals("0x" + offset + length + expected_hex);
    });

    it("allows to call symbol", async function () {
      let data = iFace.encodeFunctionData(
        // action
        "symbol",
        []
      );

      const tx_call = await customWeb3Request(context.web3, "eth_call", [
        {
          from: GENESIS_ACCOUNT,
          value: "0x0",
          gas: "0x10000",
          gasPrice: GAS_PRICE,
          to: assetAddress,
          data: data,
        },
      ]);

      let expected = stringToHex("Local");
      let offset = numberToHex(32).slice(2).padStart(64, "0");
      let length = numberToHex(5).slice(2).padStart(64, "0");
      // Bytes are padded at the end
      let expected_hex = expected.slice(2).padEnd(64, "0");
      expect(tx_call.result).equals("0x" + offset + length + expected_hex);
    });

    it("allows to call decimals", async function () {
      let data = iFace.encodeFunctionData(
        // action
        "decimals",
        []
      );

      const tx_call = await customWeb3Request(context.web3, "eth_call", [
        {
          from: GENESIS_ACCOUNT,
          value: "0x0",
          gas: "0x10000",
          gasPrice: GAS_PRICE,
          to: assetAddress,
          data: data,
        },
      ]);

      let expected = "0x" + numberToHex(12).slice(2).padStart(64, "0");
      expect(tx_call.result).equals(expected);
    });

    it("allows to call getBalance", async function () {
      let data = iFace.encodeFunctionData(
        // action
        "balanceOf",
        [BALTATHAR]
      );

      const tx_call = await customWeb3Request(context.web3, "eth_call", [
        {
          from: GENESIS_ACCOUNT,
          value: "0x0",
          gas: "0x10000",
          gasPrice: GAS_PRICE,
          to: assetAddress,
          data: data,
        },
      ]);
      let amount = new BN(100000000000000);

      let amount_hex = "0x" + bnToHex(amount).slice(2).padStart(64, "0");
      expect(tx_call.result).equals(amount_hex);
    });

    it("allows to call totalSupply", async function () {
      let data = iFace.encodeFunctionData(
        // action
        "totalSupply",
        []
      );
      const tx_call = await customWeb3Request(context.web3, "eth_call", [
        {
          from: GENESIS_ACCOUNT,
          value: "0x0",
          gas: "0x10000",
          gasPrice: GAS_PRICE,
          to: assetAddress,
          data: data,
        },
      ]);

      let amount = new BN(100000000000000);

      let amount_hex = "0x" + bnToHex(amount).slice(2).padStart(64, "0");
      expect(tx_call.result).equals(amount_hex);
    });
  },
  true
);
Example #8
Source File: test-precompile-local-assets-erc20.ts    From moonbeam with GNU General Public License v3.0 4 votes vote down vote up
describeDevMoonbeamAllEthTxTypes(
  "Precompiles - Assets-ERC20 Wasm",
  (context) => {
    let sudoAccount, baltatharAccount, assetId, iFace, assetAddress;
    before("Setup contract and mock balance", async () => {
      const keyring = new Keyring({ type: "ethereum" });
      sudoAccount = await keyring.addFromUri(ALITH_PRIV_KEY, null, "ethereum");
      baltatharAccount = await keyring.addFromUri(BALTATHAR_PRIV_KEY, null, "ethereum");

      // registerAsset
      const { events: eventsRegister } = await createBlockWithExtrinsic(
        context,
        sudoAccount,
        context.polkadotApi.tx.sudo.sudo(
          context.polkadotApi.tx.assetManager.registerLocalAsset(
            baltatharAccount.address,
            baltatharAccount.address,
            true,
            new BN(1)
          )
        )
      );

      // Look for assetId in events
      eventsRegister.forEach((e) => {
        if (e.section.toString() === "assetManager") {
          assetId = e.data[0].toHex();
        }
      });
      assetId = assetId.replace(/,/g, "");

      assetAddress = u8aToHex(new Uint8Array([...hexToU8a("0xFFFFFFFE"), ...hexToU8a(assetId)]));

      // Set metadata
      await createBlockWithExtrinsic(
        context,
        baltatharAccount,
        context.polkadotApi.tx.localAssets.setMetadata(assetId, "Local", "Local", new BN(12))
      );

      // mint asset
      await createBlockWithExtrinsic(
        context,
        baltatharAccount,
        context.polkadotApi.tx.localAssets.mint(assetId, sudoAccount.address, 100000000000000)
      );

      const contractData = await getCompiled("LocalAssetExtendedErc20Instance");
      iFace = new ethers.utils.Interface(contractData.contract.abi);
      const { contract, rawTx } = await createContract(context, "LocalAssetExtendedErc20Instance");
      const address = contract.options.address;
      await context.createBlock({ transactions: [rawTx] });
    });
    it("allows to approve transfers, and allowance matches", async function () {
      let data = iFace.encodeFunctionData(
        // action
        "approve",
        [BALTATHAR, 1000]
      );

      const tx = await createTransaction(context, {
        from: ALITH,
        privateKey: ALITH_PRIV_KEY,
        value: "0x0",
        gas: "0x200000",
        gasPrice: GAS_PRICE,
        to: assetAddress,
        data: data,
      });

      const block = await context.createBlock({
        transactions: [tx],
      });

      const receipt = await context.web3.eth.getTransactionReceipt(block.txResults[0].result);

      expect(receipt.status).to.equal(true);
      expect(receipt.logs.length).to.eq(1);
      expect(receipt.logs[0].address.toLowerCase()).to.eq(assetAddress);
      expect(receipt.logs[0].topics.length).to.eq(3);
      expect(receipt.logs[0].topics[0]).to.eq(SELECTORS.logApprove);
      let approvals = (await context.polkadotApi.query.localAssets.approvals(
        assetId,
        ALITH,
        BALTATHAR
      )) as any;

      expect(approvals.unwrap().amount.eq(new BN(1000))).to.equal(true);
    });
    it("should gather the allowance", async function () {
      let data = iFace.encodeFunctionData(
        // action
        "allowance",
        [ALITH, BALTATHAR]
      );

      const tx_call = await customWeb3Request(context.web3, "eth_call", [
        {
          from: GENESIS_ACCOUNT,
          value: "0x0",
          gas: "0x10000",
          gasPrice: GAS_PRICE,
          to: assetAddress,
          data: data,
        },
      ]);
      let amount = new BN(1000);

      let amount_hex = "0x" + bnToHex(amount).slice(2).padStart(64, "0");
      expect(tx_call.result).equals(amount_hex);
    });
  },
  true
);