@polkadot/util#numberToHex TypeScript Examples
The following examples show how to use
@polkadot/util#numberToHex.
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: test-precompile-staking.ts From moonbeam with GNU General Public License v3.0 | 6 votes |
describeDevMoonbeamAllEthTxTypes("Staking - Join Candidates", (context) => {
it("should successfully call joinCandidates on ETHAN", async function () {
const block = await sendPrecompileTx(
context,
ADDRESS_STAKING,
SELECTORS,
ETHAN,
ETHAN_PRIVKEY,
"join_candidates",
[numberToHex(Number(MIN_GLMR_STAKING)), numberToHex(1)]
);
const receipt = await context.web3.eth.getTransactionReceipt(block.txResults[0].result);
expect(receipt.status).to.equal(true);
let candidatesAfter = await context.polkadotApi.query.parachainStaking.candidatePool();
expect((candidatesAfter.toJSON() as { owner: string; amount: string }[]).length).to.equal(
2,
"New candidate should have been added"
);
expect((candidatesAfter.toJSON() as { owner: string; amount: string }[])[1].owner).to.equal(
ETHAN,
"New candidate ethan should have been added"
);
expect((candidatesAfter.toJSON() as { owner: string; amount: string }[])[1].amount).to.equal(
"0x000000000000003635c9adc5dea00000",
"new candidate ethan should have been added (wrong amount)"
);
expect(Number((await isCandidate(context, ETHAN)).result)).to.equal(1);
await verifyLatestBlockFees(context, expect, MIN_GLMR_STAKING);
});
});
Example #2
Source File: test-precompile-staking.ts From moonbeam with GNU General Public License v3.0 | 6 votes |
describeDevMoonbeamAllEthTxTypes("Staking - Join Delegators", (context) => {
beforeEach("should successfully call delegate for ETHAN to ALITH", async function () {
await sendPrecompileTx(context, ADDRESS_STAKING, SELECTORS, ETHAN, ETHAN_PRIVKEY, "nominate", [
ALITH,
numberToHex(Number(MIN_GLMR_STAKING)),
"0x0",
"0x0",
]);
});
it("should have successfully delegated ALITH", async function () {
const delegatorsAfter = (
(await context.polkadotApi.query.parachainStaking.delegatorState(ETHAN)) as any
).unwrap();
expect(
(
delegatorsAfter.toJSON() as {
delegations: { owner: string; amount: string }[];
}
).delegations[0].owner
).to.equal(ALITH, "delegation didn't go through");
expect(delegatorsAfter.status.toString()).equal("Active");
});
});
Example #3
Source File: test-precompile-staking.ts From moonbeam with GNU General Public License v3.0 | 6 votes |
describeDevMoonbeamAllEthTxTypes("Staking - Join Delegators", (context) => {
let ethan;
before("should successfully call delegate for ETHAN to ALITH", async function () {
const keyring = new Keyring({ type: "ethereum" });
ethan = await keyring.addFromUri(ETHAN_PRIVKEY, null, "ethereum");
// Delegate ETHAN->ALITH
await sendPrecompileTx(context, ADDRESS_STAKING, SELECTORS, ETHAN, ETHAN_PRIVKEY, "nominate", [
ALITH,
numberToHex(Number(MIN_GLMR_STAKING)),
"0x0",
"0x0",
]);
});
it("should verify delegation pending requests", async function () {
expect(Number((await delegationRequestIsPending(context, ETHAN, ALITH)).result)).to.equal(0);
// Schedule Revoke
await context.polkadotApi.tx.parachainStaking
.scheduleRevokeDelegation(ALITH)
.signAndSend(ethan);
await context.createBlock();
// Check that there exists a pending request
expect(Number((await delegationRequestIsPending(context, ETHAN, ALITH)).result)).to.equal(1);
});
});
Example #4
Source File: Provider.ts From evm-provider.js with Apache License 2.0 | 6 votes |
async _resolveTransaction(
tx: Deferrable<TransactionRequest>
): Promise<Deferrable<TransactionRequest>> {
for (const key of ['gasLimit', 'value']) {
const typeKey = key as 'gasLimit' | 'value';
if (tx[typeKey]) {
if (BigNumber.isBigNumber(tx[typeKey])) {
tx[typeKey] = (tx[typeKey] as BigNumber).toHexString();
} else if (isNumber(tx[typeKey])) {
tx[typeKey] = numberToHex(tx[typeKey] as number);
}
}
}
delete tx.nonce;
delete tx.gasPrice;
delete tx.chainId;
return tx;
}
Example #5
Source File: test-precompile-democracy.ts From moonbeam with GNU General Public License v3.0 | 5 votes |
describeDevMoonbeam("Democracy - propose", (context) => {
let genesisAccount: KeyringPair;
let encodedHash: `0x${string}`;
let iFace: Interface;
before("Setup genesis account for substrate", async () => {
const keyring = new Keyring({ type: "ethereum" });
genesisAccount = await keyring.addFromUri(GENESIS_ACCOUNT_PRIVATE_KEY, null, "ethereum");
iFace = await deployAndInterfaceContract(context, "Democracy");
// encodedHash
encodedHash = await notePreimagePrecompile(
context,
iFace,
context.polkadotApi.tx.parachainStaking.setParachainBondAccount(GENESIS_ACCOUNT)
);
});
it("propose", async function () {
// propose
await sendPrecompileTx(
context,
ADDRESS_DEMO_PRECOMPILE,
SELECTORS,
GENESIS_ACCOUNT,
GENESIS_ACCOUNT_PRIVATE_KEY,
"propose",
[encodedHash, numberToHex(Number(PROPOSAL_AMOUNT))]
);
// referendumCount
const referendumCount = await context.polkadotApi.query.democracy.referendumCount();
expect(referendumCount.toHuman()).to.equal("0");
// publicPropCount
const publicPropCount = await context.polkadotApi.query.democracy.publicPropCount();
expect(publicPropCount.toHuman()).to.equal("1");
// publicProps
const publicProps = await context.polkadotApi.query.democracy.publicProps();
// encodedHash
expect((publicProps.toHuman() as any)[0][1]).to.equal(encodedHash);
// prop author
expect((publicProps.toHuman() as any)[0][2]).to.equal(GENESIS_ACCOUNT);
// depositOf
const depositOf = await context.polkadotApi.query.democracy.depositOf(0);
expect((depositOf.toHuman() as any)[1]).to.equal("1,000,000,000,000,000,000,000");
});
});
Example #6
Source File: test-precompile-revert-attack.ts From moonbeam with GNU General Public License v3.0 | 5 votes |
describeDevMoonbeamAllEthTxTypes(
"Precompiles - test revert attack on state modifier",
(context) => {
it("should return contract creation gas cost", async function () {
// Check initial balance
const initialBalance = await context.web3.eth.getBalance(GENESIS_ACCOUNT);
// Deploy atatck contract
const { contract, rawTx } = await createContract(context, "StakingDelegationAttaker");
await context.createBlock({ transactions: [rawTx] });
// call the payable function, which should revert
const block = await context.createBlock({
transactions: [
await createContractExecution(
context,
{
contract,
contractCall: contract.methods.score_a_free_delegation(),
},
{
...GENESIS_TRANSACTION,
value: numberToHex(Number(MIN_GLMR_STAKING)),
}
),
],
});
// TX should be included but fail
const receipt = await context.web3.eth.getTransactionReceipt(block.txResults[0].result);
expect(receipt.status).to.eq(false);
// Delegation shouldn't have passed
const nominatorsAfter = await context.polkadotApi.query.parachainStaking.delegatorState(
GENESIS_ACCOUNT
);
expect(nominatorsAfter.toHuman()).to.eq(null);
// balance dif should only be tx fee, not MIN_GLMR_STAKING
expect(
Number(initialBalance) - Number(await context.web3.eth.getBalance(GENESIS_ACCOUNT)) <
Number(MIN_GLMR_STAKING)
).to.eq(true);
});
}
);
Example #7
Source File: test-precompile-assets-erc20.ts From moonbeam with GNU General Public License v3.0 | 4 votes |
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 #8
Source File: test-precompile-democracy.ts From moonbeam with GNU General Public License v3.0 | 4 votes |
describeDevMoonbeam("Democracy - second proposal", (context) => {
let genesisAccount: KeyringPair, alith: KeyringPair;
let encodedHash: `0x${string}`;
let launchPeriod;
let iFace: Interface;
before("Setup genesis account for substrate", async () => {
const keyring = new Keyring({ type: "ethereum" });
genesisAccount = await keyring.addFromUri(GENESIS_ACCOUNT_PRIVATE_KEY, null, "ethereum");
alith = await keyring.addFromUri(ALITH_PRIV_KEY, null, "ethereum");
iFace = await deployAndInterfaceContract(context, "Democracy");
//launchPeriod
launchPeriod = await context.polkadotApi.consts.democracy.launchPeriod;
// notePreimage
encodedHash = await notePreimagePrecompile(
context,
iFace,
context.polkadotApi.tx.parachainStaking.setParachainBondAccount(GENESIS_ACCOUNT)
);
// propose
await sendPrecompileTx(
context,
ADDRESS_DEMO_PRECOMPILE,
SELECTORS,
GENESIS_ACCOUNT,
GENESIS_ACCOUNT_PRIVATE_KEY,
"propose",
[encodedHash, numberToHex(Number(PROPOSAL_AMOUNT))]
);
// second
await sendPrecompileTx(
context,
ADDRESS_DEMO_PRECOMPILE,
SELECTORS,
ALITH,
ALITH_PRIV_KEY,
"second",
[numberToHex(0), numberToHex(1000)]
);
});
// TODO: test getters
it("second proposal", async function () {
// publicProps
const publicProps = await context.polkadotApi.query.democracy.publicProps();
// encodedHash
expect((publicProps.toHuman() as any)[0][1]).to.equal(encodedHash);
// prop author
expect((publicProps.toHuman() as any)[0][2]).to.equal(GENESIS_ACCOUNT);
// depositOf
const depositOf = await context.polkadotApi.query.democracy.depositOf(0);
expect((depositOf.toHuman() as any)[1]).to.equal("1,000,000,000,000,000,000,000");
expect((depositOf.toHuman() as any)[0][1]).to.equal(ALITH);
});
it("check launch period", async function () {
// launchPeriod
expect(launchPeriod.toHuman()).to.equal("7,200");
});
it("check referendum is up", async function () {
this.timeout(1000000);
// let Launchperiod elapse to turn the proposal into a referendum
// launchPeriod minus the 3 blocks that already elapsed
for (let i = 0; i < Number(launchPeriod) - 3; i++) {
await context.createBlock();
}
// referendumCount
let referendumCount = await context.polkadotApi.query.democracy.referendumCount();
expect(referendumCount.toHuman()).to.equal("1");
// publicPropCount
const publicPropCount = await context.polkadotApi.query.democracy.publicPropCount();
expect(publicPropCount.toHuman()).to.equal("1");
// referendumInfoOf
const referendumInfoOf = await context.polkadotApi.query.democracy.referendumInfoOf(0);
expect((referendumInfoOf.toHuman() as any).Ongoing.proposalHash).to.equal(encodedHash);
});
});
Example #9
Source File: test-precompile-democracy.ts From moonbeam with GNU General Public License v3.0 | 4 votes |
describeDevMoonbeam("Democracy - vote on referendum", (context) => {
let genesisAccount: KeyringPair, alith: KeyringPair;
let encodedHash: `0x${string}`;
let enactmentPeriod, votingPeriod;
let iFace: Interface;
before("Setup genesis account for substrate", async () => {
const keyring = new Keyring({ type: "ethereum" });
genesisAccount = await keyring.addFromUri(GENESIS_ACCOUNT_PRIVATE_KEY, null, "ethereum");
alith = await keyring.addFromUri(ALITH_PRIV_KEY, null, "ethereum");
iFace = await deployAndInterfaceContract(context, "Democracy");
// enactmentPeriod
enactmentPeriod = await context.polkadotApi.consts.democracy.enactmentPeriod;
// votingPeriod
votingPeriod = await context.polkadotApi.consts.democracy.votingPeriod;
// encodedHash
encodedHash = await notePreimagePrecompile(
context,
iFace,
context.polkadotApi.tx.parachainStaking.setParachainBondAccount(GENESIS_ACCOUNT)
);
// propose
await sendPrecompileTx(
context,
ADDRESS_DEMO_PRECOMPILE,
SELECTORS,
GENESIS_ACCOUNT,
GENESIS_ACCOUNT_PRIVATE_KEY,
"propose",
[encodedHash, numberToHex(Number(PROPOSAL_AMOUNT))]
);
// second
await sendPrecompileTx(
context,
ADDRESS_DEMO_PRECOMPILE,
SELECTORS,
ALITH,
ALITH_PRIV_KEY,
"second",
[numberToHex(0), numberToHex(1000)]
);
});
it("check enactment period", async function () {
// enactmentPeriod
expect(enactmentPeriod.toHuman()).to.equal("7,200");
});
it("check voting Period", async function () {
// votingPeriod
expect(votingPeriod.toHuman()).to.equal("36,000");
});
it("vote", async function () {
this.timeout(2000000);
// let Launchperiod elapse to turn the proposal into a referendum
// launchPeriod minus the 3 blocks that already elapsed
for (let i = 0; i < 7200 - 3; i++) {
await context.createBlock();
}
// vote
await sendPrecompileTx(
context,
ADDRESS_DEMO_PRECOMPILE,
SELECTORS,
ALITH,
ALITH_PRIV_KEY,
"standard_vote",
[numberToHex(0), "0x01", numberToHex(Number(VOTE_AMOUNT)), numberToHex(1)]
);
// referendumInfoOf
const referendumInfoOf = await context.polkadotApi.query.democracy.referendumInfoOf(0);
console.log("referendumInfoOf.toHuman() ", referendumInfoOf.toHuman());
expect((referendumInfoOf.toHuman() as any).Ongoing.proposalHash).to.equal(encodedHash);
expect((referendumInfoOf.toHuman() as any).Ongoing.tally.ayes).to.equal(
"10,000,000,000,000,000,000"
);
expect((referendumInfoOf.toHuman() as any).Ongoing.tally.turnout).to.equal(
"10,000,000,000,000,000,000"
);
// let votePeriod + enactmentPeriod elapse to turn the proposal into a referendum
for (let i = 0; i < Number(votingPeriod) + Number(enactmentPeriod) + 10; i++) {
await context.createBlock();
}
let parachainBondInfo = await context.polkadotApi.query.parachainStaking.parachainBondInfo();
expect(parachainBondInfo.toHuman()["account"]).to.equal(GENESIS_ACCOUNT);
});
});
Example #10
Source File: test-precompile-local-assets-erc20.ts From moonbeam with GNU General Public License v3.0 | 4 votes |
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
);