Execute transactions to fulfill your users' intents.
One you know how to make a request from the Lego Client, you can execute the transaction however you want.
In this example we use Viem to execute a transaction, you'll need to input the result of the SwapForNFT function and simple sign the transaction like any other.
import { createWalletClient, http } from "viem";
import { privateKeyToAccount } from "viem/accounts";
import { base } from "viem/chains";
import { LegoClient } from '@shogun-sdk/money-legos';
async function setupBuyNftWithViem() {
// 1. Initialize the Lego client
const legoClient = new LegoClient({
apiKey: "your api key here",
});
// 2. Set up your wallet
const account = privateKeyToAccount("0x..."); // Your private key
const client = createWalletClient({
chain: base,
transport: http(),
account,
});
try {
// 3. Fetch the purchase data
const { data } = await legoClient.MagicEden.SwapForNFT({
token: {
address: "0x0000000000000000000000000000000000000000", // ETH
decimals: 18,
chainId: 8453, // Base chain
},
items: [
{
address: "0x72d876d9cdf4001b836f8e47254d0551eda2eebb", // NFT contract
tokenId: "32", // NFT ID
},
],
userAddress: account.address,
});
if (!data) {
console.error("No data returned from MagicEden.SwapForNFT");
return;
}
// 4. Execute each transaction step
const { steps } = data;
for (const step of steps) {
console.log(`Executing step: ${step.description || 'Unknown step'}`);
const txHash = await client.sendTransaction({
to: step.to as `0x${string}`,
data: step.data as `0x${string}`,
value: BigInt(step.value),
chainId: step.chainId,
gas: BigInt(step.gas),
maxFeePerGas: BigInt(step.maxFeePerGas),
maxPriorityFeePerGas: BigInt(step.maxPriorityFeePerGas),
});
console.log(`Transaction successful! Hash: ${txHash}`);
}
} catch (error) {
console.error("Error during NFT purchase:", error);
}
}