Custom Approach

Smart Contract changes - Personal Signature

  1. 1.
    Inherit BasicMetaTransaction contract in your contract
  2. 2.
    Replace msg.sender in your contract with msgSender()

Smart Contract changes - EIP-712 Signature

  1. 1.
    Inherit EIP712MetaTransaction contract in your contract
  2. 2.
    Replace msg.sender in your contract with msgSender()
  3. 3.
    Deploy contract on the desired network.

Client Side changes

Now the contracts are updated and deployed, it's time to do the changes on your client-side.
  1. 1.
    After Registering Your Dapp, SmartContact & Contract method on Desired network on Biconomy Dashboard, copy the <api-key>, you will need it on the client-side code.
  2. 2.
    It is important that you need to make 2 providers on your client-side. One normal provider from your connected wallet eg window.ethereum for Metamask, to take the User Signature on the wallet pop-up window. Second provider object to be used with Biconomy to send the transaction. This second provider (network provider) should be a provider initialised with network RPC URL. That's it.
  3. 3.
    In this custom approach instead of calling you contract methods directly, you will need to call executeMetaTransaction() method and pass your contract method in functionSignature along with other params.
  4. 4.
    So the flow will be like this, to take the user signature you need to use the wallet provider. Once you get the user signature, pass that signature in the executeMetaTransaction()along with functionSignature and other params and call executeMetaTransaction() method using the second provider which was passed to Biconomy object.

SDK Integration

In basic terms, you need one provider object for sending meta transactions using Biconomy (Mexa), another for signing meta transaction parameters.

1. Importing Mexa

Via npm
Standalone JS File
1
npm install @biconomy/mexa
Copied!
1
// Install Biconomy
2
<script src="https://cdn.jsdelivr.net/npm/@biconomy/[email protected]/dist/mexa.js"></script>
3
​
4
// Import Biconomy
5
let Biconomy = window.Biconomy.default;
Copied!

2. Initializing SDK

You can use Mexa either with Web3.js or Ethers.js. We'll be making two provider objects, one linked to your dApp's network RPC, and the other to your user's wallet.
Web3 + Custom
Ethers + Custom
1
import {Biconomy} from "@biconomy/mexa";
2
​
3
// We're creating a 2nd Ethers provider linked to your L2 network of choice
4
let biconomy = new Biconomy(new Web3.providers.HttpProvider("YOUR RPC URL HERE")
5
,{apiKey: <API Key>, debug: true});
6
let biconomyWeb3 = new Web3(biconomy);
7
​
8
/*
9
This provider linked to your wallet.
10
If needed, substitute your wallet solution in place of window.ethereum
11
*/
12
let walletWeb3 = new Web3(window.ethereum);
Copied!
1
import {Biconomy} from "@biconomy/mexa";
2
​
3
// We're creating a 2nd Ethers provider linked to your L2 network of choice
4
let biconomy = new Biconomy(new ethers.providers.JsonRpcProvider("YOUR RPC URL HERE"),
5
{apiKey: <API Key>, debug: true});
6
let networkProvider = new ethers.providers.Web3Provider(biconomy);
7
​
8
/*
9
This provider linked to your wallet.
10
If needed, substitute your wallet solution in place of window.ethereum
11
*/
12
let walletProvider = new ethers.providers.Web3Provider(window.ethereum);
13
​
Copied!

3. Initialize your DApp after Mexa initialization

Mexa fetches data from Biconomy's servers. Because of this, it's best to initialize your DApp or perform any action after the biconomy.READY event occurs.
If there is an error while initializing Mexa, it's good to catch and log a biconomy.ERROR event for better debugging.
Mexa Initialization
1
biconomy.onEvent(biconomy.READY, () => {
2
// Initialize your contracts here using biconomy's provider instance
3
// Initialize dapp here like getting user accounts etc
4
}).onEvent(biconomy.ERROR, (error, message) => {
5
// Handle error while initializing mexa
6
});
Copied!

4. Sign & Send Meta Transactions

Custom + Ethers
Custom + Web3
​Check out the repository for complete example code
1
let walletProvider, walletSigner;
2
​
3
//networkProvider as defined above for ethers can be used for sendTransaction (send raw transaxction) or waitForTransaction for special cases (i.e. backend private key etc)
4
​
5
// Initialize Constants
6
const domainType = [
7
{ name: "name", type: "string" },
8
{ name: "version", type: "string" },
9
{ name: "verifyingContract", type: "address" },
10
{ name: "salt", type: "bytes32" },
11
];
12
const metaTransactionType = [
13
{ name: "nonce", type: "uint256" },
14
{ name: "from", type: "address" },
15
{ name: "functionSignature", type: "bytes" }
16
];
17
// replace the chainId 42 if network is not kovan
18
let domainData = {
19
name: "TestContract",
20
version: "1",
21
verifyingContract: config.contract.address,
22
// converts Number to bytes32. Use your own chainId instead of 42 for other networks
23
salt: ethers.utils.hexZeroPad((ethers.BigNumber.from(42)).toHexString(), 32)
24
};
25
​
26
​
27
let contract = new ethers.Contract(<CONTRACT_ADDRESS>,
28
<CONTRACT_ABI>, biconomy.getSignerByAddress(userAddress));
29
let contractInterface = new ethers.utils.Interface(<CONTRACT_ABI>);
30
​
31
/*
32
This provider is linked to your wallet.
33
If needed, substitute your wallet solution in place of window.ethereum
34
*/
35
walletProvider = new ethers.providers.Web3Provider(window.ethereum);
36
walletSigner = walletProvider.getSigner();
37
​
38
let nonce = await contract.getNonce(userAddress);
39
let functionSignature = contractInterface.encodeFunctionData("setQuote", [newQuote]);
40
41
let message = {};
42
message.nonce = parseInt(nonce);
43
message.from = userAddress;
44
message.functionSignature = functionSignature;
45
​
46
const dataToSign = JSON.stringify({
47
types: {
48
EIP712Domain: domainType,
49
MetaTransaction: metaTransactionType
50
},
51
domain: domainData,
52
primaryType: "MetaTransaction",
53
message: message
54
});
55
​
56
/*Its important to use eth_signTypedData_v3 and not v4 to get EIP712 signature
57
because we have used salt in domain data instead of chainId*/
58
// Get the EIP-712 Signature and send the transaction
59
let signature = await walletProvider.send("eth_signTypedData_v3", [userAddress, dataToSign])
60
let { r, s, v } = getSignatureParameters(signature);
61
let tx = contract.executeMetaTransaction(userAddress,
62
functionSignature, r, s, v);
63
64
await tx.wait(1);
65
console.log("Transaction hash : ", tx.hash);
66
67
68
//////////
69
/*helper*/
70
​
71
const getSignatureParameters = signature => {
72
if (!ethers.utils.isHexString(signature)) {
73
throw new Error(
74
'Given value "'.concat(signature, '" is not a valid hex string.')
75
);
76
}
77
var r = signature.slice(0, 66);
78
var s = "0x".concat(signature.slice(66, 130));
79
var v = "0x".concat(signature.slice(130, 132));
80
v = ethers.BigNumber.from(v).toNumber();
81
if (![27, 28].includes(v)) v += 27;
82
return {
83
r: r,
84
s: s,
85
v: v
86
};
87
};
Copied!
​Check out the repository for complete example code
1
// This web3 instance is used to get user signature from connected wallet
2
let walletWeb3 = new Web3(window.ethereum);
3
​
4
// Initialize constants
5
const domainType = [
6
{ name: "name", type: "string" },
7
{ name: "version", type: "string" },
8
{ name: "verifyingContract", type: "address" },
9
{ name: "salt", type: "bytes32" },
10
];
11
const metaTransactionType = [
12
{ name: "nonce", type: "uint256" },
13
{ name: "from", type: "address" },
14
{ name: "functionSignature", type: "bytes" }
15
];
16
// replace the chainId 42 if network is not kovan
17
let domainData = {
18
name: "TestContract",
19
version: "1",
20
verifyingContract: config.contract.address,
21
// converts Number to bytes32. Use your chainId instead of 42 if network is not Kovan
22
salt: '0x' + (42).toString(16).padStart(64, '0')
23
​
24
​
25
let contract = new biconomyWeb3.eth.Contract(
26
<Your Contract ABI>,
27
<Your Contract Address>
28
);
29
30
let nonce = await contract.methods.getNonce(userAddress).call();
31
// Create your target method signature.. here we are calling setQuote() method of our contract
32
let functionSignature = contract.methods.setQuote(newQuote).encodeABI();
33
let message = {};
34
message.nonce = parseInt(nonce);
35
message.from = userAddress;
36
message.functionSignature = functionSignature;
37
​
38
const dataToSign = JSON.stringify({
39
types: {
40
EIP712Domain: domainType,
41
MetaTransaction: metaTransactionType
42
},
43
domain: domainData,
44
primaryType: "MetaTransaction",
45
message: message
46
});
47
​
48
// NOTE: Using walletWeb3 here, as it is connected to the wallet where user account is present.
49
// Get the EIP-712 Signature and send the transaction
50
walletWeb3.currentProvider.send({
51
jsonrpc: "2.0",
52
id: 999999999999,
53
method: "eth_signTypedData_v4",
54
params: [userAddress, dataToSign]
55
},function(error, response) {
56
// Check github repository for getSignatureParameters helper method
57
let { r, s, v } = getSignatureParameters(response.result);
58
59
let tx = contract.methods.executeMetaTransaction(userAddress,
60
functionSignature, r, s, v)
61
.send(from: userAddress);
62
​
63
tx.on("transactionHash", function(hash) {
64
// Handle transaction hash
65
}).once("confirmation", function(confirmationNumber, receipt) {
66
// Handle confirmation
67
}).on("error", function(error) {
68
// Handle error
69
});
70
71
}
72
);
Copied!
​
Last modified 10mo ago