Dive into secure and efficient coding practices with our curated list of the top 10 examples showcasing 'eth-sig-util' in functional components in JavaScript. Our advanced machine learning engine meticulously scans each line of code, cross-referencing millions of open source libraries to ensure your implementation is not just functional, but also robust and secure. Elevate your React applications to new heights by mastering the art of handling side effects, API calls, and asynchronous operations with confidence and precision.
//data = data2;
// eth_util.toBuffer
//var msg_hash = eth_sig_utils.typedSignatureHash(data.message);
//console.log("MSGHASH", msg_hash);
var msg_hash = utils.hashStruct(data.primaryType, data.message, data.types);
console.log('MSG_HASH = ', eth_util.bufferToHex(msg_hash));
var msg_sig = eth_sig_utils.signTypedData(key, {data: data})
console.log("Ok, signed typed data using " + account.address)
console.log("SIGNATURE = " + msg_sig);
var signer = eth_sig_utils.recoverTypedSignature({data: data, sig: msg_sig});
signer = w3_utils.toChecksumAddress(signer);
if (signer === account.address) {
console.log("Ok, verified signature was signed by " + signer);
} else {
console.log("ERROR: signature verification failed");
}
// const typedData = {
// types: {
// EIP712Domain: [
// { name: 'name', type: 'string' },
// { name: 'version', type: 'string' },
// { name: 'chainId', type: 'uint256' },
// { name: 'verifyingContract', type: 'address' },
// ],
'amount': new BigNumber('35000000000000000000'),
'balance': 2000,
},
}
//console.log(data);
//var key = eth_util.toBuffer(buyer_key_bytes);
var key = eth_util.toBuffer(buyer_key);
// eth_util.toBuffer
var sig = eth_sig_utils.signTypedData(key, {data: data})
console.log("Ok, signed typed data using " + account.address)
console.log("SIGNATURE = " + sig);
var signer = eth_sig_utils.recoverTypedSignature({data, sig});
signer = w3_utils.toChecksumAddress(signer);
if (signer === account.address) {
console.log("Ok, verified signature was signed by " + signer);
} else {
console.log("ERROR: signature verification failed");
}
// dicether/eip712
// eth-sig-util
// eth_sig_utils.signTypedData
// eth_sig_utils.recoverTypedSignature
// https://github.com/MetaMask/eth-sig-util#signtypeddata-privatekeybuffer-msgparams
// https://github.com/MetaMask/eth-sig-util#signtypeddata-privatekeybuffer-msgparams
var w3_utils = require("web3-utils");
var eth_sig_utils = require("eth-sig-util");
var eth_accounts = require("web3-eth-accounts");
var eth_util = require("ethereumjs-util");
const utils = eth_sig_utils.TypedDataUtils;
var buyer_key = "0x" + "a4985a2ed93107886e9a1f12c7b8e2e351cc1d26c42f3aab7f220f3a7d08fda6";
var buyer_key_bytes = w3_utils.hexToBytes(buyer_key);
const consumer_key = '0x395df67f0c2d2d9fe1ad08d1bc8b6627011959b79c53d7dd6a3536a33ab8a4fd';
const consumer_delegate_key = '0xe485d098507f54e7733a205420dfddbe58db035fa577fc294ebd14db90767a52';
var account = new eth_accounts().privateKeyToAccount(consumer_key);
var addr = eth_util.toBuffer(account.address);
console.log("Using private key: " + buyer_key);
//console.log(buyer_key_bytes);
//console.log(account);
console.log("Account canonical address: " + account.address);
//console.log(addr);
const data3 = {
value = 4 * 10 ** decimals;
from = newAccount.address;
// to = strangerAccount;
// from = account1;
to = web3m.eth.accounts.create().address;
delegate = dreamTeamAccount;
fee = 2 * 10 ** decimals - 1;
deadline = (await web3m.eth.getBlock(`latest`)).timestamp + 60 * 60 * 24 * 7; // +7 days
usedSigId = sigId++;
const dataToSign = getTypedDataToSign();
await token.transfer(from, 4 * (value + fee), { from: dreamTeamAccount });
const balanceFrom = +(await token.balanceOf.call(from));
assert.equal(balanceFrom, 4 * (value + fee), "Account balance must be refilled");
const balanceTo = +(await token.balanceOf.call(to));
const balanceDelegate = +(await token.balanceOf.call(delegate));
signature = sigUtils.signTypedData(
Buffer.from(newAccount.privateKey.slice(2), "hex"),
{ data: dataToSign }
);
const tx = await token.transferViaSignature(
from, to, value, fee, delegate, deadline, usedSigId, signature, SIG_STANDARD_TYPED, { from: delegate }
);
infoLog(`TX (transferViaSignature) gas usage: ${ getUsedGas(tx) }`);
assert.equal(+(await token.balanceOf(from)), balanceFrom - value - fee, "Must subtract balance");
assert.equal(+(await token.balanceOf(to)), balanceTo + value, "Must add balance to recipient");
assert.equal(+(await token.balanceOf(delegate)), balanceDelegate + fee, "Must pay fee to delegate");
});
async verifyListingSignature(listing, signer) {
// grab the raw ipfs hash
const ipfs_response = await this.ipfsService.loadFile(listing.ipfs.hash)
const ipfs_data = await ipfs_response.json()
const signature = ipfs_data.signature
delete ipfs_data.signature
listing.raw_ipfs_hash = this.contractService.web3.utils.sha3(stringify(ipfs_data))
const signData = await this.contractService.getSignListingData(listing)
const recoveredAddress = recoverTypedSignature({ data: signData, sig: signature })
delete listing.raw_ipfs_hash
if (recoveredAddress == signer.toLowerCase()) {
return true
}
console.log('Signature verification failed:', signData, ' recovered address:', recoveredAddress, ' signer:', signer)
}
const result = await promisify<{ result: string, error: Error }>(
this.web3.currentProvider, 'sendAsync'
)({
method: 'eth_signTypedData',
params: [params, this.channel.account],
from: this.channel.account
});
if (result.error)
throw result.error;
sign = result.result;
} catch (err) {
if (err.message && err.message.includes('User denied')) {
throw err;
}
console.log('Error on signTypedData', err);
const hash = typedSignatureHash(params);
// ask for signing of the hash
sign = await this.signMessage(hash);
}
//debug
const recovered = recoverTypedSignature({ data: params, sig: sign });
console.log('signTypedData =', sign, recovered);
proof.sign = sign;
// return signed message
if (proof.balance === this.channel.proof.balance) {
this.setChannel(Object.assign(
{},
this.channel,
{ proof, next_proof: proof }
));
let msgParams = [
{
type: 'string', // Any valid solidity type
name: 'Message', // Any string label you want
value: 'Vote for ' + candidateName // The value to sign
}
]
var from = web3.eth.accounts[0]
var params = [msgParams, from]
var method = 'eth_signTypedData'
console.log("Hash is ");
console.log(sigUtil.typedSignatureHash(msgParams));
web3.currentProvider.sendAsync({
method,
params,
from,
}, function (err, result) {
if (err) return console.dir(err)
if (result.error) {
alert(result.error.message)
}
if (result.error) return console.error(result)
$("#msg").html("User wants to vote for " + candidateName + ". Any one can now submit the vote to the blockchain on behalf of this user. Use the below values to submit the vote to the blockchain");
$("#vote-for").html("Candidate: " + candidateName);
$("#addr").html("Address: " + from);
$("#signature").html("Signature: " + result.result);
console.log('PERSONAL SIGNED:' + JSON.stringify(result.result))
function signatureDigest (hashed, priv) {
let buffedHash = byteArrToBuffer(hashed)
let buffedPriv = byteArrToBuffer(priv)
// let toBuffer = EthUtil.toBuffer(hashed)
let ecSigned = EthUtil.ecsign(buffedHash, buffedPriv)
let rpcSig = EthUtil.bufferToHex(sigUtil.concatSig(ecSigned.v, ecSigned.r, ecSigned.s))
let rpcSigInByte = hexToByteArr(rpcSig)
debug(`low level signature signed by private key is: ${rpcSigInByte}`)
return rpcSigInByte
}
let returnData = {}
returnData.signature = result.result
// ensure that the signature matches
const recoveredAddress = ethUtil.toChecksumAddress(ethSigUtil.recoverTypedSignature({
data: typedData,
sig: returnData.signature
}))
if (ethUtil.toChecksumAddress(recoveredAddress) !== from) {
return reject(Error(
`The returned signature '${returnData.signature}' originated from '${recoveredAddress}', not '${from}'.`
))
}
returnData.from = from
returnData.messageHash = ethSigUtil.typedSignatureHash(typedData)
const signature = ethUtil.fromRpcSig(returnData.signature)
returnData.r = ethUtil.addHexPrefix(Buffer.from(signature.r).toString('hex'))
returnData.s = ethUtil.addHexPrefix(Buffer.from(signature.s).toString('hex'))
returnData.v = signature.v
resolve(returnData)
})
})
it('returns the expected value', async () => {
const typedData = {
types: {
EIP712Domain: []
},
domain: {},
primaryType: 'EIP712Domain',
message: {}
}
await keyring.deserialize([privKeyHex])
const sig = await keyring.signTypedData_v4(address, typedData)
const restored = sigUtil.recoverTypedSignature({ data: typedData, sig: sig })
assert.equal(restored, address, 'recovered address')
})
})