ethereumjs-util#fromRpcSig TypeScript Examples

The following examples show how to use ethereumjs-util#fromRpcSig. 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: permit.ts    From solidity-utils with MIT License 6 votes vote down vote up
/*
 * @param permitContract The contract object with ERC20Permit type and token address for which the permit creating.
 */
export async function getPermit (
    owner: string,
    ownerPrivateKey: string,
    permitContract: PermittableToken,
    tokenVersion: string,
    chainId: number,
    spender: string,
    value: string,
    deadline = defaultDeadline
) {
    const nonce = await permitContract.nonces(owner);
    const name = await permitContract.name();
    const data = buildData(name, tokenVersion, chainId, permitContract.address, owner, spender, value, nonce.toString(), deadline);
    const signature = signWithPk(ownerPrivateKey, data);
    const { v, r, s } = fromRpcSig(signature);
    const permitCall = permitContract.contract.methods.permit(owner, spender, value, deadline, v, r, s).encodeABI();
    return cutSelector(permitCall);
}
Example #2
Source File: permit.ts    From solidity-utils with MIT License 6 votes vote down vote up
/*
 * @param permitContract The contract object with ERC20PermitLikeDai type and token address for which the permit creating.
 */
export async function getPermitLikeDai (
    holder: string,
    holderPrivateKey: string,
    permitContract: PermittableToken,
    tokenVersion: string,
    chainId: number,
    spender: string,
    allowed: boolean,
    expiry = defaultDeadline
) {
    const nonce = await permitContract.nonces(holder);
    const name = await permitContract.name();
    const data = buildDataLikeDai(name, tokenVersion, chainId, permitContract.address, holder, spender, nonce.toString(), allowed, expiry);
    const signature = signWithPk(holderPrivateKey, data);
    const { v, r, s } = fromRpcSig(signature);
    const permitCall = permitContract.contract.methods.permit(holder, spender, nonce, expiry, allowed, v, r, s).encodeABI();
    return cutSelector(permitCall);
}
Example #3
Source File: utils.ts    From core with GNU General Public License v3.0 6 votes vote down vote up
export async function signPermit(
  owner: Wallet,
  toAddress: string,
  tokenAddress: string,
  tokenId: number,
  chainId: number
) {
  return new Promise<EIP712Sig>(async (res, reject) => {
    let nonce;
    const mediaContract = MediaFactory.connect(tokenAddress, owner);

    try {
      nonce = (
        await mediaContract.permitNonces(owner.address, tokenId)
      ).toNumber();
    } catch (e) {
      console.error('NONCE', e);
      reject(e);
      return;
    }

    const deadline = Math.floor(new Date().getTime() / 1000) + 60 * 60 * 24; // 24 hours
    const name = await mediaContract.name();

    try {
      const sig = signTypedData(Buffer.from(owner.privateKey.slice(2), 'hex'), {
        data: {
          types: {
            EIP712Domain: [
              { name: 'name', type: 'string' },
              { name: 'version', type: 'string' },
              { name: 'chainId', type: 'uint256' },
              { name: 'verifyingContract', type: 'address' },
            ],
            Permit: [
              { name: 'spender', type: 'address' },
              { name: 'tokenId', type: 'uint256' },
              { name: 'nonce', type: 'uint256' },
              { name: 'deadline', type: 'uint256' },
            ],
          },
          primaryType: 'Permit',
          domain: {
            name,
            version: '1',
            chainId,
            verifyingContract: mediaContract.address,
          },
          message: {
            spender: toAddress,
            tokenId,
            nonce,
            deadline,
          },
        },
      });
      const response = fromRpcSig(sig);
      res({
        r: response.r,
        s: response.s,
        v: response.v,
        deadline: deadline.toString(),
      });
    } catch (e) {
      console.error(e);
      reject(e);
    }
  });
}
Example #4
Source File: utils.ts    From core with GNU General Public License v3.0 6 votes vote down vote up
export async function signMintWithSig(
  owner: Wallet,
  tokenAddress: string,
  creator: string,
  contentHash: string,
  metadataHash: string,
  creatorShare: BigNumberish,
  chainId: number
) {
  return new Promise<EIP712Sig>(async (res, reject) => {
    let nonce;
    const mediaContract = MediaFactory.connect(tokenAddress, owner);

    try {
      nonce = (await mediaContract.mintWithSigNonces(creator)).toNumber();
    } catch (e) {
      console.error('NONCE', e);
      reject(e);
      return;
    }

    const deadline = Math.floor(new Date().getTime() / 1000) + 60 * 60 * 24; // 24 hours
    const name = await mediaContract.name();

    try {
      const sig = signTypedData(Buffer.from(owner.privateKey.slice(2), 'hex'), {
        data: {
          types: {
            EIP712Domain: [
              { name: 'name', type: 'string' },
              { name: 'version', type: 'string' },
              { name: 'chainId', type: 'uint256' },
              { name: 'verifyingContract', type: 'address' },
            ],
            MintWithSig: [
              { name: 'contentHash', type: 'bytes32' },
              { name: 'metadataHash', type: 'bytes32' },
              { name: 'creatorShare', type: 'uint256' },
              { name: 'nonce', type: 'uint256' },
              { name: 'deadline', type: 'uint256' },
            ],
          },
          primaryType: 'MintWithSig',
          domain: {
            name,
            version: '1',
            chainId,
            verifyingContract: mediaContract.address,
          },
          message: {
            contentHash,
            metadataHash,
            creatorShare,
            nonce,
            deadline,
          },
        },
      });
      const response = fromRpcSig(sig);
      res({
        r: response.r,
        s: response.s,
        v: response.v,
        deadline: deadline.toString(),
      });
    } catch (e) {
      console.error(e);
      reject(e);
    }
  });
}
Example #5
Source File: is-signer.test.ts    From ethereum-sdk with MIT License 6 votes vote down vote up
describe.each(providers)("isSigner", (ethereum) => {
	test("recover works for hw wallets workaround", async () => {
		const hash = randomWord()

		const pk = Buffer.from(randomWord().substring(2), "hex")
		const wallet = new Wallet(pk)

		const signature = personalSign(pk, { data: hash })
		const sig = fromRpcSig(signature)
		const fixed = toRpcSig(sig.v + 4, sig.r, sig.s)
		expect(await isSigner(null as any, wallet.getAddressString(), Buffer.from(hash.substring(2), "hex"), fixed))
			.toBe(true)
	})

	test("erc1271 works", async () => {
		const test = await deployTestErc1271(web3)
		const from = await ethereum.getFrom()
		const hash = Buffer.from(randomWord().substring(2), "hex")
		const pk = Buffer.from(randomWord().substring(2), "hex")
		const signature = personalSign(pk, { data: randomWord() })

		await test.methods.setReturnSuccessfulValidSignature(false).send({ from })
		expect(await isSigner(ethereum, test.options.address, hash, signature)).toBe(false)

		await test.methods.setReturnSuccessfulValidSignature(true).send({ from })
		expect(await isSigner(ethereum, test.options.address, hash, signature)).toBe(true)
	})
})
Example #6
Source File: Permitable.test.ts    From solidity-utils with MIT License 4 votes vote down vote up
contract('Permitable', function ([wallet1, wallet2]) {
    const initContext = async () => {
        const permittableMock = await PermitableMock.new();
        const chainId = await web3.eth.getChainId();
        const account = await web3.eth.accounts.create();
        const wallet = {
            address: account.address,
            privateKey: account.privateKey,
        };
        const owner = wallet.address;
        const holder = owner;
        const erc20PermitMock: types.ERC20PermitMockInstance = undefined!;
        const daiLikePermitMock: types.DaiLikePermitMockInstance = undefined!;
        return { permittableMock, chainId, wallet, owner, holder, erc20PermitMock, daiLikePermitMock };
    };

    let context: Awaited<ReturnType<typeof initContext>> = undefined!;

    before(async () => {
        context = await initContext();
    });

    beforeEach(async function () {
        context.erc20PermitMock = await ERC20PermitMock.new('USDC', 'USDC', wallet1, toBN(100));
        context.daiLikePermitMock = await DaiLikePermitMock.new('DAI', 'DAI', wallet1, toBN(100));
    });

    it('should be permitted for IERC20Permit', async function () {
        const permit = await getPermit(context.owner, context.wallet.privateKey, context.erc20PermitMock, '1', context.chainId, wallet2, value.toString());
        await context.permittableMock.__permit(context.erc20PermitMock.address, permit);
        expect(await context.erc20PermitMock.nonces(context.owner)).to.be.bignumber.equal('1');
        expect(await context.erc20PermitMock.allowance(context.owner, wallet2)).to.be.bignumber.equal(value);
    });

    it('should not be permitted for IERC20Permit', async function () {
        const data = buildData(await context.erc20PermitMock.name(), '1', context.chainId, context.erc20PermitMock.address, context.owner, wallet2, value.toString(), nonce);
        const signature = signWithPk(context.wallet.privateKey, data);
        const { v, r, s } = fromRpcSig(signature);

        const permit = web3.eth.abi.encodeParameter(
            'tuple(address,address,uint256,uint256,uint8,bytes32,bytes32)',
            [context.owner, wallet1, value, defaultDeadline, v, r, s],
        );
        await expect(context.permittableMock.__permit(context.erc20PermitMock.address, permit))
            .to.eventually.be.rejectedWith('ERC20Permit: invalid signature');
    });

    it('should be permitted for IDaiLikePermit', async function () {
        const permit = await getPermitLikeDai(context.holder, context.wallet.privateKey, context.daiLikePermitMock, '1', context.chainId, wallet2, true);
        await context.permittableMock.__permit(context.daiLikePermitMock.address, permit);

        const MAX_UINT128 = toBN('2').pow(toBN('128')).sub(toBN('1'));
        expect(await context.daiLikePermitMock.nonces(context.owner)).to.be.bignumber.equal('1');
        expect(await context.daiLikePermitMock.allowance(context.owner, wallet2)).to.be.bignumber.equal(MAX_UINT128);
    });

    it('should not be permitted for IDaiLikePermit', async function () {
        const data = buildDataLikeDai(await context.daiLikePermitMock.name(), '1', context.chainId, context.daiLikePermitMock.address, context.holder, wallet2, nonce, true);
        const signature = signWithPk(context.wallet.privateKey, data);
        const { v, r, s } = fromRpcSig(signature);

        const payload = web3.eth.abi.encodeParameter(
            'tuple(address,address,uint256,uint256,bool,uint8,bytes32,bytes32)',
            [context.holder, wallet1, nonce, defaultDeadline, true, v, r, s],
        );

        await expect(context.permittableMock.__permit(context.daiLikePermitMock.address, payload))
            .to.eventually.be.rejectedWith('Dai/invalid-permit');
    });

    it('should be wrong permit length', async function () {
        const data = buildData(await context.erc20PermitMock.name(), '1', context.chainId, context.erc20PermitMock.address, context.owner, wallet2, value.toString(), nonce);
        const signature = signWithPk(context.wallet.privateKey, data);
        const { v, r, s } = fromRpcSig(signature);

        const permit = web3.eth.abi.encodeParameter(
            'tuple(address,uint256,uint256,uint8,bytes32,bytes32)',
            [wallet2, value, defaultDeadline, v, r, s],
        );

        await expect(context.permittableMock.__permit(context.erc20PermitMock.address, permit))
            .to.eventually.be.rejectedWith('BadPermitLength()');
    });
});