一个简单的EIP712

本地签名
  1. 定义签名体:例
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:签名携带的信息

  1. 调用小狐狸(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:得到签名信息

  1. 操作合约签名信息(前提是合约里使用了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:不知道什么意思,合约验证签名需要用的

  • 7
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 Rust 中,可以使用 `ethers-rs` crate 来实现 EIP712 签名。以下是一个示例代码: 首先,你需要在 `Cargo.toml` 文件中添加 `ethers-rs` crate 的依赖: ``` [dependencies] ethers = "0.3.0-alpha.5" ``` 接下来,你可以使用以下代码实现 EIP712 签名: ```rust use ethers::types::{Address, Name, TypedData}; use ethers::utils::{keccak256, hash_message, bytes_to_hex_str}; use ethers::signers::{LocalWallet, Signer}; fn main() { // 创建钱包 let wallet = LocalWallet::new(&mut rand::thread_rng()); // EIP712 消息 let message = TypedData { types: Default::default(), domain: Default::default(), message: vec![ ( "name".to_string(), "Hello".to_string(), ), ( "value".to_string(), 42u64.into(), ), ], }; // 计算消息哈希 let message_hash = keccak256(&message.to_bytes()).to_fixed_bytes(); // 签名 let signature = wallet.sign_message(&message_hash).unwrap(); // 打印签名结果 println!("Signature: {}", bytes_to_hex_str(&signature)); // 验证签名 let signer_address = Address::from(wallet.address()); let recovered_address = hash_message(&message.to_bytes(), &signature).unwrap(); assert_eq!(signer_address, recovered_address); } ``` 在这个示例中,我们首先创建了一个本地钱包。然后,我们定义了一个 EIP712 消息,包含一个名为 `name` 的字符串和一个名为 `value` 的整数。我们计算了消息哈希,并使用钱包的 `sign_message` 方法对其进行签名。最后,我们打印签名结果,并验证签名。 请注意,这个示例中的 EIP712 消息是一个自定义的示例消息。如果你要使用真实的 EIP712 消息,请参考对应协议的文档,以获取正确的类型定义和域名设置。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值