本地签名
- 定义签名体:例
const createDelegateBySigMessage = (compAddress, delegatee, expiry = 10e9, chainId = 1, nonce = 0) => {
const types = {
EIP712Domain: [
{
name: 'name',
type: 'string'
},
{
name: 'chainId',
type: 'uint256'
},
{
name: 'verifyingContract',
type: 'address'
}
],
Delegation: [
{
name: 'delegatee',
type: 'address'
},
{
name: 'nonce',
type: 'uint256'
},
{
name: 'expiry',
type: 'uint256'
}
]
};
const primaryType = 'Delegation';
const domain = {
name: 'Compound',
chainId: '',
verifyingContract: compAddress
};
const message = {
delegatee,
nonce,
expiry
};
return JSON.stringify({ types, primaryType, domain, message });
};
// 参数介绍
compAddress: 合约地址
delegatee: 委托地址
expiry: 签名到期时间
chainId: 链id
nonce: 地址在合约中交易随机数
types:格式规定,暂时没有找到其他写法
primaryType: 看着像是与types第二个key保持一致
domain:定义名字、链与合约地址
message:签名携带的信息
- 调用小狐狸(MateMask)的window.ethereum.sendAsync
window.ethereum.sendAsync({
method: 'eth_signTypedData_v4',
params: [myAccount, msgParams],
from: myAccount
}, async (err, result) => {
if (err) {
console.error('ERROR', err);
alert(err);
return;
} else if (result.error) {
console.error('ERROR', result.error.message);
alert(result.error.message);
return;
}
const sig = result.result;
delegatee.value = _delegatee;
nonce.value = _nonce;
expiry.value = _expiry;
signature.value = sig;
console.log('signature', sig);
console.log('msgParams', JSON.parse(msgParams));
});
// 参数介绍:
method:eth_signTypeData_v4 小狐狸给定的签名方法
params:[x,y] x:操作合约的地址 y:通过createDelegateBySigMessage得到的签名体
from:签名的地址
回调(err,resutl)
err:错误信息
result:得到签名信息
- 操作合约签名信息(前提是合约里使用了EIP712规范的函数)
const r = '0x' + sig.substring(2).substring(0, 64);
const s = '0x' + sig.substring(2).substring(64, 128);
const v = '0x' + sig.substring(2).substring(128, 130);
currentDelegatee = await comp.methods.delegates(myAccount).call();
myDelegatee.innerText = currentDelegatee;
console.log(`Now delegated to: ${currentDelegatee}`);
console.log('delegatee', _delegatee);
console.log('nonce', _nonce);
console.log('expiry', _expiry);
console.log('v', v);
console.log('r', r);
console.log('s', s);
const tx = await comp.methods.delegateBySig(_delegatee, _nonce, _expiry, v, r, s).send({
from: myAccount,
gasLimit: web3.utils.toHex(1000000),
gasPrice: web3.utils.toHex(25000000000),
});
console.log('delegateBySig Transaction', tx);
currentDelegatee = await comp.methods.delegates(myAccount).call();
myDelegatee.innerText = currentDelegatee;
console.log(`Now delegated to: ${currentDelegatee}`);
// 参数介绍
sig:通过上一步得到的签名信息=[lkkm
r、s、v:不知道什么意思,合约验证签名需要用的