Using SDK
Gasless SDK (EOA) enables meta transactions or gasless transactions in your dApp out of the box.
Biconomy's SDK is a typescript based implementation that can be easily integrated into your dApp. The SDK can be used on client side code running in a browser or a javascript/typescript based dApp running on a backend server.
It works alongside your existing Web3/Ethers library by acting as a Web3/Ether provider that submits meta transactions to our relayer infrastructure - instead of directly to the network.
This section is divided into Frontend and Backend integration of SDK. You can choose either of them based on your requirement.
SDK Frontend Integration
1. Installing and importing SDK
Biconomy Gasless SDK can be installed either via npm or yarn repository
npm install @biconomy/mexa
yarn add @biconomy/mexa
You can use Gasless either with Web3.js or Ethers.js library. It works with both libraries.
const biconomy = new Biconomy(window.ethereum as ExternalProvider, {
apiKey: config.apiKey.prod,
debug: true,
contractAddresses: [<contractAddress1>, <contractAddress2>], // list of contract address you want to enable gasless on
});
// The first argument of the Biconomy class is an EIP 1193 type provider that has to be passed.
// If there is a type mismatch you'll have to set the type of the provider as
// External Provider
export type ExternalProvider = {
isMetaMask?: boolean;
isStatus?: boolean;
host?: string;
path?: string;
sendAsync?: (request: { method: string, params?: Array<any> }, callback: (error: any, response: any) => void) => void
send?: (request: { method: string, params?: Array<any> }, callback: (error: any, response: any) => void) => void
request?: (request: { method: string, params?: Array<any> }) => Promise<any>
}
// To create contract instances you can do:
const contractInstance = new ethers.Contract(
config.contract.address,
config.contract.abi,
biconomy.ethersProvider
);
2. Initialize your dApp after SDK initialization
You need to call the init method. This method makes calls to the Biconomy backend to fetch data that you registered on the dashbaord.
await biconomy.init();
Done! Interact with Web3/Ethers the same way you have been doing before!
Now, whenever a contract call is made (provided that it is registered in the Dashboard) Gasless SDK will ask for the user's signature and handle the transaction - rather than sending a signed transaction directly to the blockchain from the user's wallet. The message the user will be prompted to sign will be in an eth_personalsign
format by default.
Refer to this link for extensive code examples for you to interact with the SDK.
Congratulations π
You have now enabled meta transactions in your dApp.
SDK Backend Integration
Here, we provide more freedom to the developer in case you want to use Biconomy in the project running at the backend where a raw transaction is signed by the user's private key.
Integration Steps
Initialize the Gasless SDK in the same way as mentioned above.
There is no change in the way you send the transactions from the backend except adding the extra information about the signature type.
Passing extra information using web3
web3.eth.sendSignedTransaction(data, callback)
will be used here but with parameters mentioned below
Parameters
data
A JSON object containing the user's signature, the raw transaction, forward request object and signature type. Data to be signed can be generated using the methodgetForwardRequestAndMessageToSign(rawTransaction)
callback
Optional callback, returns an error object as first parameter and the result as second.
Returns
PromiEvent
A promise combined event emitter. Will be resolved when the transaction receipt is available
Passing extra information using ethers
provider.send("eth_sendRawTransaction", [data], callback)
will be used here but with parameters mentioned below
Parameters
data
A JSON object containing the user's signature, the raw transaction, forward request object and signature type. Data to be signed can be generated using the methodgetForwardRequestAndMessageToSign(rawTransaction)
callback
Optional callback, returns an error object as first parameter and the result as second.
Returns
Promise
A promise which will not resolve until the transaction hash is mined. Promise resolves with transaction hash. One can use the event emitter method of ethers provider to get the mined transaction receipts.
Example Code
Check the repository here for complete example code
let sigUtil = require("eth-sig-util"); // additional dependency
// Initialize constants
let contract = new web3.eth.Contract(
<CONTRACT_ABI>,
<CONTRACT_ADDRESS>
);
let userAddress = <selected address>;
let privateKey = <PRIVATE_KEY>;
let txParams = {
"from": userAddress,
//gasLimit is optional or can be pre estimated for your method call before passing
"gasLimit": web3.utils.toHex(300000),
"to": <CONTRACT_ADDRESS>,
//optional. Note: Native meta transactions would not work if your method call is expecting ether value transfer and has checkes on msg.value
"value": "0x0",
//Call your target method. here we are calling setQuote() method of our contract
"data": contract.methods.setQuote(newQuote).encodeABI(),
};
const signedTx = await web3.eth.accounts.signTransaction(txParams, `0x${privateKey}`);
const forwardData = await biconomy.getForwardRequestAndMessageToSign(signedTx.rawTransaction);
const signature = sigUtil.signTypedMessage(new Buffer.from(privateKey, 'hex'),
{ data: forwardData.eip712Format }, 'V4');
// forwardData has personalSignatureFormat available as well. Check the next tab on the right
let rawTransaction = signedTx.rawTransaction;
let data = {
signature: signature,
forwardRequest: forwardData.request,
rawTransaction: rawTransaction,
signatureType: biconomy.EIP712_SIGN
};
// Get the transaction Hash using the Event Emitter returned
web3.eth.sendSignedTransaction(data)
.on('transactionHash', (hash)=> {
console.log(`Transaction hash is ${hash}`)
})
.once('confirmation', (confirmation, receipt)=> {
console.log(`Transaction Confirmed.`);
console.log(receipt);
//do Something
});
/********* OR *********/
// Use any one of the methods below to check for transaction confirmation
// USING PROMISE
let receipt = await web3.eth.sendSignedTransaction(data, (error, txHash)=>{
if(error) {
return console.error(error);
}
console.log(txHash);
});
Last updated
Was this helpful?