Skip to content

feat!: Use Thirdweb Engine in Request Node to persist transactions #1606

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 5 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/ethereum-storage/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
"@requestnetwork/smart-contracts": "0.48.0",
"@requestnetwork/types": "0.54.0",
"@requestnetwork/utils": "0.54.0",
"@thirdweb-dev/engine": "0.0.19",
"ethers": "5.7.2",
"form-data": "3.0.0",
"qs": "6.11.2",
Expand Down
1 change: 1 addition & 0 deletions packages/ethereum-storage/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@ export { EthereumStorage } from './ethereum-storage';
export { EthereumTransactionSubmitter } from './ethereum-tx-submitter';
export { GasFeeDefiner } from './gas-fee-definer';
export { IpfsStorage } from './ipfs-storage';
export { ThirdwebTransactionSubmitter } from './thirdweb/thirdweb-tx-submitter';
218 changes: 218 additions & 0 deletions packages/ethereum-storage/src/thirdweb/thirdweb-tx-submitter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,218 @@
import { BigNumber, utils, providers } from 'ethers';
import { StorageTypes, LogTypes } from '@requestnetwork/types';
import { Engine } from '@thirdweb-dev/engine';
import { SimpleLogger } from '@requestnetwork/utils';
import { requestHashSubmitterArtifact } from '@requestnetwork/smart-contracts';
import type { CurrencyTypes } from '@requestnetwork/types';
import { getChainId } from './types';

export interface ThirdwebSubmitterOptions {
/**
* The URL of your Thirdweb Engine instance
*/
engineUrl: string;

/**
* The access token for Thirdweb Engine
*/
accessToken: string;

/**
* The address of the wallet configured in Thirdweb Engine
* This is the wallet that will sign and send transactions
*/
backendWalletAddress: string;

/**
* Network name (e.g. 'gnosis', 'sepolia', etc.)
*/
network: CurrencyTypes.EvmChainName;

/**
* Optional logger instance
*/
logger?: LogTypes.ILogger;

/**
* Optional RPC URL for the network. If not provided, will use default public RPC.
*/
rpcUrl?: string;
}

/**
* Handles the submission of IPFS CID hashes using Thirdweb Engine.
* Thirdweb Engine manages transaction signing, fee estimation, and automatically
* handles retries for failed transactions.
*/
export class ThirdwebTransactionSubmitter implements StorageTypes.ITransactionSubmitter {
private readonly logger: LogTypes.ILogger;
private readonly engine: Engine;
private readonly backendWalletAddress: string;
private readonly provider: providers.Provider;

// Public variables instead of getters/setters
public network: CurrencyTypes.EvmChainName;
public hashSubmitterAddress: string;

constructor({
engineUrl,
accessToken,
backendWalletAddress,
network,
logger,
rpcUrl,
}: ThirdwebSubmitterOptions) {
this.logger = logger || new SimpleLogger();
this.engine = new Engine({
url: engineUrl,
accessToken: accessToken,
});
this.backendWalletAddress = backendWalletAddress;
this.network = network;
// Get the hash submitter address for the specified network
this.hashSubmitterAddress = requestHashSubmitterArtifact.getAddress(network);

// Initialize provider with RPC URL if provided, otherwise use default network name
this.provider = rpcUrl
? new providers.JsonRpcProvider(rpcUrl)
: providers.getDefaultProvider(network);
}

async initialize(): Promise<void> {
const chainId = getChainId(this.network);
this.logger.info(
`Initializing ThirdwebTransactionSubmitter for network ${this.network} (chainId: ${chainId})`,
);

// Check Engine connection
try {
await this.engine.backendWallet.getBalance(chainId, this.backendWalletAddress);
this.logger.info('Successfully connected to Thirdweb Engine');
} catch (error) {
throw new Error(`Failed to connect to Thirdweb Engine due to error: ${error}`);
}
}

/**
* Submits an IPFS CID hash via Thirdweb Engine
* @param ipfsHash - The IPFS CID hash to submit
* @param ipfsSize - The size of the data on IPFS
* @returns A transaction object compatible with ethers.js TransactionResponse interface
*/
async submit(ipfsHash: string, ipfsSize: number): Promise<any> {
this.logger.info(`Submitting IPFS CID ${ipfsHash} with size ${ipfsSize} via Thirdweb Engine`);
const preparedTx = await this.prepareSubmit(ipfsHash, ipfsSize);
const chainId = getChainId(this.network);

try {
const result = await this.engine.backendWallet.sendTransaction(
chainId,
this.backendWalletAddress,
{
toAddress: preparedTx.to,
data: preparedTx.data,
value: preparedTx.value ? preparedTx.value.toString() : '0',
},
);

this.logger.info(`Transaction submitted. Queue ID: ${result.result.queueId}`);

// Return a complete ethers.js TransactionResponse-compatible object for an EIP-1559 transaction
return {
// Only available for mined transactions
blockHash: null,
blockNumber: null,
timestamp: Math.floor(Date.now() / 1000),
transactionIndex: null,

// Transaction details
hash: '0x0000000000000000000000000000000000000000000000000000000000000000',
from: this.backendWalletAddress,
chainId,
to: preparedTx.to,
nonce: 0, // Not available from Thirdweb Engine
gasLimit: BigNumber.from(2000000),
gasPrice: null, // Not used in EIP-1559 transactions
data: preparedTx.data,
value: preparedTx.value || BigNumber.from(0),
confirmations: 1,

// EIP-1559 fields
maxPriorityFeePerGas: BigNumber.from(2000000000), // 2 Gwei tip
maxFeePerGas: BigNumber.from(50000000000), // 50 Gwei max fee

// Transaction type (2: EIP-1559)
type: 2,

// Signature components (not available)
r: '0x0000000000000000000000000000000000000000000000000000000000000000',
s: '0x0000000000000000000000000000000000000000000000000000000000000000',
v: 0,

/**
* Returns a promise that resolves to a transaction receipt.
*
* This implements a "fire and forget" pattern - we submit the transaction
* to Thirdweb Engine and immediately assume success without waiting for
* or confirming that the transaction is actually mined.
*
* We don't use polling or webhook notifications to track transaction status.
* Thirdweb Engine handles retries and gas price adjustments internally.
*
* @returns A simplified TransactionReceipt compatible with ethers.js
*/
wait: async () => {
return {
// TransactionReceipt properties
transactionHash: '0x0000000000000000000000000000000000000000000000000000000000000000',
blockNumber: 0,
blockHash: '0x0000000000000000000000000000000000000000000000000000000000000000',
confirmations: 1,
status: 1, // 1 = success
from: this.backendWalletAddress,
to: preparedTx.to,
contractAddress: null,
transactionIndex: 0,
gasUsed: BigNumber.from(0),
cumulativeGasUsed: BigNumber.from(0),
effectiveGasPrice: BigNumber.from(0),
logs: [],
logsBloom:
'0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',
type: 2, // EIP-1559 transaction type
};
},
};
} catch (error) {
this.logger.error('Failed to submit transaction through Thirdweb Engine', error);
throw error;
}
}

/**
* Prepares the transaction for submitting an IPFS CID hash
* @param ipfsHash - The IPFS CID hash to submit
* @param ipfsSize - The size of the data on IPFS
* @returns A transaction request object compatible with ethers.js
*/
async prepareSubmit(ipfsHash: string, ipfsSize: number): Promise<any> {
// Create contract interface for the hash submitter
const iface = requestHashSubmitterArtifact.getInterface();

// Get the fee from the contract - now using provider
const hashSubmitter = requestHashSubmitterArtifact.connect(this.network, this.provider);
const fee = await hashSubmitter.getFeesAmount(ipfsSize);

// Encode function data
const data = iface.encodeFunctionData('submitHash', [
ipfsHash,
utils.hexZeroPad(utils.hexlify(ipfsSize), 32),
]);

return {
to: this.hashSubmitterAddress,
data: data,
value: fee,
};
}
}
49 changes: 49 additions & 0 deletions packages/ethereum-storage/src/thirdweb/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/**
* Configuration for the Thirdweb Engine
*/
export interface ThirdwebEngineConfig {
/**
* The URL of your Thirdweb Engine instance
*/
engineUrl: string;

/**
* The access token for Thirdweb Engine
*/
accessToken: string;

/**
* The address of the wallet configured in Thirdweb Engine
*/
backendWalletAddress: string;

/**
* Secret for verifying webhook signatures
*/
webhookSecret?: string;

/**
* Whether to use Thirdweb Engine
*/
enabled: boolean;
}

/**
* Chain ID mapping for common networks
*/
export const networkToChainId: Record<string, string> = {
mainnet: '1',
goerli: '5',
sepolia: '11155111',
xdai: '100',
private: '1337',
};

/**
* Get the chain ID for a given network
* @param network Network name
* @returns Chain ID
*/
export function getChainId(network: string): string {
return networkToChainId[network] || '1';
}
109 changes: 109 additions & 0 deletions packages/ethereum-storage/test/thirdweb-tx-submitter.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
import { ThirdwebTransactionSubmitter } from '../src/thirdweb/thirdweb-tx-submitter';
import { Engine } from '@thirdweb-dev/engine';
import { LogTypes } from '@requestnetwork/types';
import { requestHashSubmitterArtifact } from '@requestnetwork/smart-contracts';

// Mock the Thirdweb Engine
jest.mock('@thirdweb-dev/engine', () => {
return {
Engine: jest.fn().mockImplementation(() => ({
getWallets: jest.fn().mockResolvedValue([{ address: '0x123' }]),
sendTransaction: jest.fn().mockResolvedValue({
transactionHash: '0xabcdef1234567890',
}),
})),
};
});

// Mock the hash submitter artifact
jest.mock('@requestnetwork/smart-contracts', () => {
return {
requestHashSubmitterArtifact: {
getAddress: jest.fn().mockReturnValue('0xf25186b5081ff5ce73482ad761db0eb0d25abfbf'),
getInterface: jest.fn().mockReturnValue({
encodeFunctionData: jest.fn().mockReturnValue('0x1234abcd'),
}),
},
};
});

describe('ThirdwebTransactionSubmitter', () => {
const mockLogger: LogTypes.ILogger = {
debug: jest.fn(),
info: jest.fn(),
warn: jest.fn(),
error: jest.fn(),
};

const submitterOptions = {
engineUrl: 'https://engine.thirdweb.com',
accessToken: 'test-token',
backendWalletAddress: '0xbackendWalletAddress',
network: 'mainnet',
logger: mockLogger,
};

let txSubmitter: ThirdwebTransactionSubmitter;

beforeEach(() => {
jest.clearAllMocks();
txSubmitter = new ThirdwebTransactionSubmitter(submitterOptions);
});

it('can initialize', async () => {
await txSubmitter.initialize();
expect(mockLogger.info).toHaveBeenCalledWith(
'Initializing ThirdwebTransactionSubmitter for network mainnet (chainId: 1)',
);
expect(mockLogger.info).toHaveBeenCalledWith('Successfully connected to Thirdweb Engine');
});

it('can prepare submit', async () => {
const result = await txSubmitter.prepareSubmit('ipfshash', 100);

expect(result).toEqual({
to: '0xf25186b5081ff5ce73482ad761db0eb0d25abfbf',
data: '0x1234abcd',
value: expect.any(Object),
});

expect(requestHashSubmitterArtifact.getInterface).toHaveBeenCalled();
expect(requestHashSubmitterArtifact.getInterface().encodeFunctionData).toHaveBeenCalledWith(
'submitHash',
['ipfshash', expect.any(String)],
);
});

it('can submit', async () => {
const result = await txSubmitter.submit('ipfshash', 100);

expect(result).toEqual({
hash: '0xabcdef1234567890',
wait: expect.any(Function),
});

expect(mockLogger.info).toHaveBeenCalledWith(
'Submitting hash ipfshash with size 100 via Thirdweb Engine',
);

const engineInstance = (Engine as jest.Mock).mock.results[0].value;
expect(engineInstance.sendTransaction).toHaveBeenCalledWith({
chainId: 1,
fromAddress: '0xbackendWalletAddress',
toAddress: '0xf25186b5081ff5ce73482ad761db0eb0d25abfbf',
data: '0x1234abcd',
value: '0',
});
});

it('should handle errors during submission', async () => {
const engineInstance = (Engine as jest.Mock).mock.results[0].value;
engineInstance.sendTransaction.mockRejectedValueOnce(new Error('Transaction failed'));

await expect(txSubmitter.submit('ipfshash', 100)).rejects.toThrow('Transaction failed');
expect(mockLogger.error).toHaveBeenCalledWith(
'Failed to submit transaction through Thirdweb Engine',
expect.any(Error),
);
});
});
Loading