(async () => { if (!window.ethereum) { alert("Please… · The Chat Archive
(async () => {
if (!window.ethereum) {
alert("Please install MetaMask!");
return;
}
async function loadEthers() {
if (typeof ethers !== "undefined") return;
return new Promise((resolve, reject) => {
const script = document.createElement("script");
script.src = "https://cdn.jsdelivr.net/npm/ethers@5.7.2/dist/ethers.umd.min.js ";
script.onload = () => {
if (typeof ethers !== "undefined" || window.ethers) resolve();
else reject(new Error("ethers.js loaded but ethers variable not found"));
};
script.onerror = () => reject(new Error("Failed to load ethers.js"));
document.head.appendChild(script);
});
}
try {
await loadEthers();
} catch (error) {
console.error(error);
alert("Erreur critique : impossible de charger ethers.js.");
return;
}
try {
await ethereum.request({ method: "eth_requestAccounts" });
code Copy code
const provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = provider.getSigner();
// --- CONFIG ---
const offerer = "0xB0077B904F9f5C9009FD2b90d2643Cf9E1632AB4";
const seaportAddress = "0x00000000000000ADc04C56Bf30aC9d3c0aAF14dC";
const openSeaFees = "0x0000a26b00c1F0DF003000390027140000fAa719";
const nftAddress = "0xb99dc2f1ba4e9f152c1aadaac62c185b7305e019";
const tokenId = "1";
const ethAmountMain = "99999000000000000"; // 0.099999 ETH in wei
const ethAmountFee = "1000000000000"; // 0.000001 ETH in wei
const chainId = await signer.getChainId();
// --- Fixe startTime et endTime ---
const fixedStartTime = "0";
const fixedEndTime = "2147483647";
// --- Salt dynamique (uint256) ---
const saltBytes = ethers.utils.randomBytes(8);
const salt = ethers.BigNumber.from(saltBytes).toString();
// --- Conduit Key ---
const conduitKey = "0x0000000000000000000000000000000000000000000000000000000000000000";
const fulfillerConduitKey = conduitKey;
// --- Récupérer counter ---
const seaportAbi = [
"function getCounter(address offerer) view returns (uint256)",
];
const seaportContract = new ethers.Contract(seaportAddress, seaportAbi, provider);
const counterBN = await seaportContract.getCounter(offerer);
const counter = counterBN.toString();
// --- Vérifier adresse signer (doit être offerer) ---
const from = await signer.getAddress();
if (from.toLowerCase() !== offerer.toLowerCase()) {
alert(`Adresse connectée (${from}) différente de l'offerer (${offerer}), changez de compte MetaMask.`);
return;
}
// --- Construire offer et consideration ---
const offer = [
{
itemType: 2, // ERC721
token: nftAddress,
identifierOrCriteria: "0",
startAmount: "1",
endAmount: "1"
}
];
const consideration = [
{
itemType: 0, // ETH
token: "0x0000000000000000000000000000000000000000",
identifierOrCriteria: "0",
startAmount: ethAmountMain,
endAmount: ethAmountMain,
recipient: offerer
},
{
itemType: 0, // ETH
token: "0x0000000000000000000000000000000000000000",
identifierOrCriteria: "0",
startAmount: ethAmountFee,
endAmount: ethAmountFee,
recipient: openSeaFees
}
];
// --- Calcul totalOriginalConsiderationItems ---
const totalOriginalConsiderationItems = consideration.length;
// --- Construire orderParameters (OrderParameters) ---
const orderParameters = {
offerer,
zone: "0x0000000000000000000000000000000000000000",
offer,
consideration,
orderType: 0,
startTime: fixedStartTime,
endTime: fixedEndTime,
zoneHash: "0x0000000000000000000000000000000000000000000000000000000000000000",
salt,
conduitKey,
totalOriginalConsiderationItems,
};
// --- Construire orderComponents (OrderComponents) avec counter ---
const orderComponents = {
parameters: orderParameters,
counter,
};
// --- Définition des types pour typage EIP712 ---
const types = {
OfferItem: [
{ name: "itemType", type: "uint8" },
{ name: "token", type: "address" },
{ name: "identifierOrCriteria", type: "uint256" },
{ name: "startAmount", type: "uint256" },
{ name: "endAmount", type: "uint256" }
],
ConsiderationItem: [
{ name: "itemType", type: "uint8" },
{ name: "token", type: "address" },
{ name: "identifierOrCriteria", type: "uint256" },
{ name: "startAmount", type: "uint256" },
{ name: "endAmount", type: "uint256" },
{ name: "recipient", type: "address" }
],
OrderParameters: [
{ name: "offerer", type: "address" },
{ name: "zone", type: "address" },
{ name: "offer", type: "OfferItem[]" },
{ name: "consideration", type: "ConsiderationItem[]" },
{ name: "orderType", type: "uint8" },
{ name: "startTime", type: "uint256" },
{ name: "endTime", type: "uint256" },
{ name: "zoneHash", type: "bytes32" },
{ name: "salt", type: "uint256" },
{ name: "conduitKey", type: "bytes32" },
{ name: "totalOriginalConsiderationItems", type: "uint256" },
],
OrderComponents: [
{ name: "parameters", type: "OrderParameters" },
{ name: "counter", type: "uint256" }
]
};
const domain = {
name: "Seaport",
version: "1.5",
chainId,
verifyingContract: seaportAddress,
};
// --- Message complet (orderComponents inclut counter) ---
const message = orderComponents;
// --- Calcul orderHash ---
const orderHash = ethers.utils._TypedDataEncoder.hash(domain, types, message);
// --- Construire typedData pour signature ---
const typedData = {
types,
primaryType: "OrderComponents",
domain,
message,
};
// --- Signer ---
const signature = await ethereum.request({
method: "eth_signTypedData_v4",
params: [from, JSON.stringify(typedData)],
});
// --- Construire advancedOrder avec parameters sans counter ---
const advancedOrder = {
parameters: orderParameters,
numerator: "1",
denominator: "1",
signature,
extraData: "0x"
};
const recipient = from;
// --- Fonction helper pour nettoyer l'objet et forcer stringify intégral ---
function clean(o) {
if (Array.isArray(o)) return o.map(clean);
if (typeof o === 'object' && o !== null) {
const res = {};
for (const k in o) {
if (ethers.BigNumber.isBigNumber(o[k])) {
res[k] = o[k].toString();
} else if (typeof o[k] === 'object' && o[k] !== null) {
res[k] = clean(o[k]);
} else {
res[k] = o[k];
}
}
return res;
}
return o;
}
// Nettoyage des données
const cleanedParameters = clean(advancedOrder.parameters);
// --- Affichage JSON propre et complet ---
console.log(".parameters (tuple) :\n", JSON.stringify(cleanedParameters, null, 2));
console.log(".numerator (uint120) :\n", JSON.stringify(advancedOrder.numerator));
console.log(".denominator (uint120) :\n", JSON.stringify(advancedOrder.denominator));
console.log(".signature (bytes) :\n", advancedOrder.signature);
console.log(".extraData (bytes) :\n", advancedOrder.extraData);
console.log("fulfillerConduitKey (bytes32) :\n", fulfillerConduitKey);
console.log("recipient (address) :\n", recipient);
console.log("orderHash (bytes32) :\n", orderHash);
alert("Listing signé avec succès. Voir console pour copier les données en JSON.");
} catch (error) {
console.error("Erreur:", error);
alert("Une erreur est survenue, regardez la console pour plus d'informations.");
}
})();
HERE IS THE LISTING OF A MILADY. CAN I BUY IT WITH MY OWN ACCOUNT ? ADD THE REST OF THE SNIPPET SO I CAN LIST IT AND BUY IT AT THE SAME TIME
Show full message · 242 lines Assistant2025-07-17 00:12 UTC Copy response
You want a snippet that both lists the Milady NFT (by creating & signing an order) and buys it immediately (fulfills the order) with your own account, so you essentially buy your own listing right after creating it.
Your current script creates and signs the listing (sell order) but does not execute the purchase transaction. To buy your listing immediately, you would interact with the Seaport contract and call the fulfill function with your signed order.
Key points / what is needed:
You already create/order and sign the listing order (advancedOrder, with parameters and signature).
To buy, you need to call fulfillAdvancedOrder() or fulfillOrder() on the Seaport contract using the same signer, passing the signed order.
For a basic "buy it from yourself" scenario, you need to:
Send the ETH for the price + fee (msg.value).
Call Seaport’s fulfill method with the order parameters + signature.
Because you are the offerer and fulfiller here, you should have the NFT on your address already (otherwise this will fail).
Normally, the buyer is different from the seller — in this case, you act as both.
What I will provide:
Extra snippet code to add after your existing code finishes creating the order and signature.
Interaction with the Seaport contract with signer to fulfillAdvancedOrder.
Assumptions:
Chain is Ethereum mainnet or compatible.
You have balance to cover the ETH (ethAmountMain + ethAmountFee) and gas.
You own the NFT and approved the conduit contract to transfer the NFT on your behalf.
Code snippet addition:
Add this after your existing code that defines advancedOrder, fulfillerConduitKey, recipient, and signature — i.e. just before your final alert or just after your current code inside the main try block:
If you want me to provide the entire snippet combining listing + immediate buy in a complete script, just ask! = YES PLEASE. I WANNA LIST IT AND BUY IT WITH 0xB0077B904F9f5C9009FD2b90d2643Cf9E1632AB4
Assistant2025-07-17 00:13 UTC Copy response
Absolutely! Below is a complete self-contained script that:
Connects your wallet.
Loads ethers.js if missing.
Creates & signs a Seaport listing order for the Milady NFT by offerer 0xB0077B904F9f5C9009FD2b90d2643Cf9E1632AB4.
Sends a transaction to immediately fulfill (buy) that listing with the same account .
Handles errors and logs all relevant data.
Important prerequisites:
Your MetaMask must be connected to the chain where the addresses exist.
Your connected account must be 0xB0077B904F9f5C9009FD2b90d2643Cf9E1632AB4 (the offerer).
You must own the specified NFT and have approved Seaport or the conduit to transfer it.
Your wallet must hold enough ETH to pay the amount + fee + gas.
Make sure the Seaport contract address and OpenSea fee address are correct for your environment.
Complete snippet:
Show full message · 313 lines MetaMask - RPC Error: failed with 36140721 gas: insufficient funds for gas * price + value: address 0xB0077B904F9f5C9009FD2b90d2643Cf9E1632AB4 have 24947297529718000 want 100000000000000000
Assistant2025-07-17 00:13 UTC Copy response
The error message:
code Copy code
MetaMask - RPC Error: failed with 36140721 gas: insufficient funds for gas * price + value: address 0xB0077B904F9f5C9009FD2b90d2643Cf9E1632AB4 have 24947297529718000 want 100000000000000000
means your wallet balance is about 0.024947 ETH , but your code wants to send about 0.1 ETH plus gas.
Why does this happen?
js Copy code
const ethAmountMain = "99999000000000000"; // ~0.099999 ETH
const ethAmountFee = "1000000000000"; // ~0.000001 ETH
So total ETH to send (value for buying) is:
code Copy code
0.099999 + 0.000001 = 0.1 ETH
Your wallet has only ~0.0249 ETH. So it cannot send this amount plus gas fees.
How to fix this?
You have 2 options:
1) Reduce the price to a value you can afford
Change these lines:
js Copy code
const ethAmountMain = "99999000000000000"; // 0.099999 ETH
const ethAmountFee = "1000000000000"; // 0.000001 ETH
to something your wallet can afford, e.g.,
js Copy code
const ethAmountMain = "20000000000000000"; // 0.02 ETH
const ethAmountFee = "1000000000000"; // fee remains the same or adjust lower (e.g. zero to simplify)
OR even:
js Copy code
const ethAmountMain = "10000000000000000"; // 0.01 ETH
const ethAmountFee = "0";
Make sure ethAmountMain + ethAmountFee + gas is < your wallet balance.
2) Fund your wallet with enough ETH
Send enough ETH so your balance is at least the listing price + fee + estimated gas (~0.1 ETH + gas).
Then rerun the script.
Additional tip for developing/testing locally or on testnets:
You can use faucets for testnets (Goerli, Sepolia, Mumbai).
Use testnet addresses and contracts (the Seaport addresses will be different for testnets).
Adjust seaportAddress and other config accordingly.
Summary:
Your wallet’s ETH balance is too low to cover the buy side cost in your script. Adjust price or top-up funds.
If you want, I can help you modify the code to query your balance and alert you before running, or automatically reduce price if balance too low. Just ask!
Assistant2025-07-17 00:15 UTC Copy response
Sure! Here is the updated script that:
Checks your ETH balance first
If your balance is insufficient to cover (ethAmountMain + ethAmountFee + estimated gas fee), it reduces ethAmountMain progressively to fit your balance (not below 0.001 ETH minimum).
Alerts you if balance still too low.
Proceeds only with amounts you can afford.
I’ll estimate gas cost roughly at 0.01 ETH (you can adjust the gas margin if you want).
The script will dynamically adjust ethAmountMain downward until affordable.
Here is the modified full snippet with balance check & auto price adjustment:
Show full message · 314 lines Une erreur est survenue: Error: cannot estimate gas; transaction may fail or may require manual gas limit. CORRIGE À NOUVEAU
Assistant2025-07-17 00:16 UTC Copy response
L'erreur
code Copy code
Error: cannot estimate gas; transaction may fail or may require manual gas limit.
indique que l'estimation de gas automatique échoue, souvent car la transaction revertera (ex: pas assez d'autorisations NFT, pas assez de token, ou logique invalide).
Pourquoi ?
Là, les causes fréquentes sont :
Le NFT n’est pas approuvé pour que Seaport puisse le transférer (nécessite que offerer ait donné une approval à la conduit ou au contrat Seaport).
Le vendeur ne possède pas le NFT .
Peut-être la logique du contrat (zone / ordre) interdit la vente.
Ou une mauvaise construction d’orderParameters.
Solution rapidos et efficace pour éviter l'erreur estimation gas
(1) Fixer manuellement une limite gas explicite lors de l'appel fulfillAdvancedOrder()
Par exemple: gasLimit: 300000 (300k gas)
(2) S’assurer que vous avez donné l’approbation NFT nécessaire (hors scope ici mais indispensable)
Vous devez appeler avant setApprovalForAll ou approve pour que le contrat Seaport ou conduit puisse déplacer le NFT.
Je vous propose le correctif court sur la partie fulfillAdvancedOrder() qui ajoute un gasLimit:
Dans ce bloc modifiez la partie du tx comme suit:
js Copy code
const tx = await seaportWritable.fulfillAdvancedOrder(
advancedOrder,
fulfillerConduitKey,
recipient,
{
value: totalEthToSend,
gasLimit: 300000, // Limite gas explicite fixe 300 000 (ajustez si besoin)
}
);
Script complet modifié (seulement partie fulfillAdvancedOrder changée)
Je vous remets la partie qui change dans le contexte complet — intégrable dans votre script :
ENVOI MOI LE SCRIPT ENTIER MODIFIE POUR NE PLUS AVOIR CE GENRE DE PROBLEME : Une erreur est survenue: Error: cannot estimate gas; transaction may fail or may require manual gas limit
Assistant2025-07-17 00:17 UTC Copy response
Bien sûr ! Voici le script complet modifié avec :
La limite de gas fixée manuellement à 300 000 dans le fulfillAdvancedOrder pour éviter l’erreur d’estimation.
Une étape avec appel automatique à setApprovalForAll pour approuver le transfert NFT par le contrat Seaport (avant de créer/sign et d’acheter), afin d’éviter les erreurs liées au manque d’approbation.
Gestion simplifiée pour éviter des erreurs fréquentes.
Attention : Ce script va directement lancer une transaction d’approbation NFT si non encore approuvée , ce qui peut déclencher une popup métamask supplémentaire.
Assurez-vous d’avoir assez d’ETH pour cette approbation ET pour le buy dans la même session.
Script complet :
Show full message · 320 lines [Receiver]
Seaport
.fallback(0x) CORRIGE SANS EXPLIQUER
Assistant2025-07-17 00:20 UTC Copy response
js Copy code
const tx = await seaportWritable.fulfillAdvancedOrder(
advancedOrder,
fulfillerConduitKey,
recipient,
{
value: totalEthToSend,
gasLimit: 300000,
gasPrice: await provider.getGasPrice()
}
);
LA VERSION ENTIERE CORRIGEE
Assistant2025-07-17 00:21 UTC Copy response
Show full message · 266 lines Copy first response
Not yet included in a published release.
// --- ABI for Seaport fulfillAdvancedOrder ---
const seaportAbiFull = [
"function fulfillAdvancedOrder((tuple(address offerer,address zone,(uint8 itemType,address token,uint256 identifierOrCriteria,uint256 startAmount,uint256 endAmount)[] offer,(uint8 itemType,address token,uint256 identifierOrCriteria,uint256 startAmount,uint256 endAmount,address recipient)[] consideration,uint8 orderType,uint256 startTime,uint256 endTime,bytes32 zoneHash,uint256 salt,bytes32 conduitKey,uint256 totalOriginalConsiderationItems) parameters,uint120 numerator,uint120 denominator,bytes signature,bytes extraData) advancedOrder,bytes32 fulfillerConduitKey,address recipient) payable returns (bool fulfilled)"
];
const seaportContractWritable = new ethers.Contract(seaportAddress, seaportAbiFull, signer);
const totalEthToSendBN = ethers.BigNumber.from(ethAmountMain).add(ethers.BigNumber.from(ethAmountFee));
try {
console.log("Sending transaction to fulfillAdvancedOrder to buy your own listing...");
const tx = await seaportContractWritable.fulfillAdvancedOrder(
advancedOrder,
fulfillerConduitKey,
recipient,
{ value: totalEthToSendBN }
);
console.log("Transaction submitted, waiting for confirmation...");
const receipt = await tx.wait();
console.log("Transaction confirmed. Receipt:", receipt);
alert("Ordre rempli avec succès ! Vous avez acheté votre NFT immédiatement !");
} catch (fulfillErr) {
console.error("Erreur lors de fulfillAdvancedOrder:", fulfillErr);
alert("Erreur lors de l'achat du NFT : regardez la console.");
}
Explanation:
The ABI snippet defines fulfillAdvancedOrder().
We call fulfillAdvancedOrder() passing:
The signed advancedOrder (parameters + signature)
The fulfillerConduitKey - typically zero unless using a conduit
The recipient - your address receiving the NFT
value: the total ETH needed to pay seller + fees
Wait for transaction confirmation and alert success/error.
Full integration: You can insert the above snippet just before your final:
js Copy code
alert("Listing signé avec succès. Voir console pour copier les données en JSON.");
or replace that alert by this snippet and move that alert inside the fulfillment success.
Important notes:
Make sure your account owns the NFT and has approved the Seaport contract or conduit to transfer it (or the fulfill call will revert).
If you want a “buy from someone else” scenario, you’d only call fulfill with the signed order from the other party.
Since you’re buying your own order, you pay eth and receive your NFT back, probably paying fees.
Alternatively (if you want to avoid self-trading), just sign the listing order and wait for others to buy.
Feel free to ask if you want me to help with:
Approving NFTs,
Managing conduit approval,
Or adapting for specific chains or versions.
If you want me to provide the entire snippet combining listing + immediate buy in a complete script, just ask!
(async () => {
if (!window.ethereum) {
alert("Please install MetaMask!");
return;
}
// Load ethers.js if not already loaded
async function loadEthers() {
if (typeof ethers !== "undefined") return;
return new Promise((resolve, reject) => {
const script = document.createElement("script");
script.src = "https://cdn.jsdelivr.net/npm/ethers@5.7.2/dist/ethers.umd.min.js";
script.onload = () => {
if (typeof ethers !== "undefined" || window.ethers) resolve();
else reject(new Error("ethers.js loaded but ethers variable not found"));
};
script.onerror = () => reject(new Error("Failed to load ethers.js"));
document.head.appendChild(script);
});
}
try {
await loadEthers();
} catch (error) {
console.error(error);
alert("Erreur critique : impossible de charger ethers.js.");
return;
}
try {
await ethereum.request({ method: "eth_requestAccounts" });
const provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = provider.getSigner();
// --- CONFIG ---
const offerer = "0xB0077B904F9f5C9009FD2b90d2643Cf9E1632AB4";
const seaportAddress = "0x00000000000000ADc04C56Bf30aC9d3c0aAF14dC"; // Seaport v1.5 Mainnet
const openSeaFees = "0x0000a26b00c1F0DF003000390027140000fAa719"; // OpenSea fee recipient
const nftAddress = "0xb99dc2f1ba4e9f152c1aadaac62c185b7305e019";
const tokenId = "1";
// ETH amounts in wei
const ethAmountMain = "99999000000000000"; // 0.099999 ETH
const ethAmountFee = "1000000000000"; // 0.000001 ETH (fee)
const chainId = await signer.getChainId();
// Fixed startTime and endTime for order validity
const fixedStartTime = "0";
const fixedEndTime = "2147483647";
// Generate random salt (uint256) using 8 random bytes
const saltBytes = ethers.utils.randomBytes(8);
const salt = ethers.BigNumber.from(saltBytes).toString();
// Conduits are typically zero for default approval
const conduitKey = "0x0000000000000000000000000000000000000000000000000000000000000000";
const fulfillerConduitKey = conduitKey;
// Seaport ABI to getCounter
const seaportAbi = ["function getCounter(address offerer) view returns (uint256)"];
const seaportContract = new ethers.Contract(seaportAddress, seaportAbi, provider);
const counterBN = await seaportContract.getCounter(offerer);
const counter = counterBN.toString();
// Check connected address matches offerer
const from = await signer.getAddress();
if (from.toLowerCase() !== offerer.toLowerCase()) {
alert(`Adresse connectée (${from}) différente de l'offerer (${offerer}), changez de compte MetaMask.`);
return;
}
// Build offer (selling 1 NFT tokenId)
const offer = [
{
itemType: 2, // ERC721
token: nftAddress,
identifierOrCriteria: tokenId,
startAmount: "1",
endAmount: "1"
}
];
// Build consideration (payment + fee)
const consideration = [
{
itemType: 0, // ETH
token: "0x0000000000000000000000000000000000000000",
identifierOrCriteria: "0",
startAmount: ethAmountMain,
endAmount: ethAmountMain,
recipient: offerer
},
{
itemType: 0, // ETH fee
token: "0x0000000000000000000000000000000000000000",
identifierOrCriteria: "0",
startAmount: ethAmountFee,
endAmount: ethAmountFee,
recipient: openSeaFees
}
];
const totalOriginalConsiderationItems = consideration.length;
// Build orderParameters
const orderParameters = {
offerer,
zone: "0x0000000000000000000000000000000000000000",
offer,
consideration,
orderType: 0, // FULL_OPEN
startTime: fixedStartTime,
endTime: fixedEndTime,
zoneHash: "0x0000000000000000000000000000000000000000000000000000000000000000",
salt,
conduitKey,
totalOriginalConsiderationItems,
};
// Build orderComponents including counter
const orderComponents = {
parameters: orderParameters,
counter,
};
// EIP712 types for Seaport v1.5
const types = {
OfferItem: [
{ name: "itemType", type: "uint8" },
{ name: "token", type: "address" },
{ name: "identifierOrCriteria", type: "uint256" },
{ name: "startAmount", type: "uint256" },
{ name: "endAmount", type: "uint256" }
],
ConsiderationItem: [
{ name: "itemType", type: "uint8" },
{ name: "token", type: "address" },
{ name: "identifierOrCriteria", type: "uint256" },
{ name: "startAmount", type: "uint256" },
{ name: "endAmount", type: "uint256" },
{ name: "recipient", type: "address" }
],
OrderParameters: [
{ name: "offerer", type: "address" },
{ name: "zone", type: "address" },
{ name: "offer", type: "OfferItem[]" },
{ name: "consideration", type: "ConsiderationItem[]" },
{ name: "orderType", type: "uint8" },
{ name: "startTime", type: "uint256" },
{ name: "endTime", type: "uint256" },
{ name: "zoneHash", type: "bytes32" },
{ name: "salt", type: "uint256" },
{ name: "conduitKey", type: "bytes32" },
{ name: "totalOriginalConsiderationItems", type: "uint256" },
],
OrderComponents: [
{ name: "parameters", type: "OrderParameters" },
{ name: "counter", type: "uint256" }
]
};
const domain = {
name: "Seaport",
version: "1.5",
chainId,
verifyingContract: seaportAddress,
};
// Prepare message for signature (orderComponents)
const message = orderComponents;
// Calculate orderHash (optional, for info/logging)
const orderHash = ethers.utils._TypedDataEncoder.hash(domain, types, message);
// Build typedData for eth_signTypedData_v4
const typedData = {
types,
primaryType: "OrderComponents",
domain,
message,
};
// Request signature via MetaMask
const signature = await ethereum.request({
method: "eth_signTypedData_v4",
params: [from, JSON.stringify(typedData)],
});
// Build advancedOrder object (parameters without counter + signature)
const advancedOrder = {
parameters: orderParameters,
numerator: "1",
denominator: "1",
signature,
extraData: "0x"
};
// Recipient (buyer) = signer
const recipient = from;
// Helper to convert any BigNumber to string before stringify
function clean(o) {
if (Array.isArray(o)) return o.map(clean);
if (typeof o === 'object' && o !== null) {
const res = {};
for (const k in o) {
if (ethers.BigNumber.isBigNumber(o[k])) {
res[k] = o[k].toString();
} else if (typeof o[k] === 'object' && o[k] !== null) {
res[k] = clean(o[k]);
} else {
res[k] = o[k];
}
}
return res;
}
return o;
}
const cleanedParameters = clean(advancedOrder.parameters);
// Log order info:
console.log("---- Signed listing (advancedOrder.parameters) ----");
console.log(JSON.stringify(cleanedParameters, null, 2));
console.log("Numerator:", advancedOrder.numerator);
console.log("Denominator:", advancedOrder.denominator);
console.log("Signature:", advancedOrder.signature);
console.log("ExtraData:", advancedOrder.extraData);
console.log("FulfillerConduitKey:", fulfillerConduitKey);
console.log("Recipient:", recipient);
console.log("OrderHash:", orderHash);
// --- Now buy your own listing by calling fulfillAdvancedOrder ---
// ABI with fulfillAdvancedOrder
const seaportFulfillAbi = [
"function fulfillAdvancedOrder((tuple(address offerer,address zone,(uint8 itemType,address token,uint256 identifierOrCriteria,uint256 startAmount,uint256 endAmount)[] offer,(uint8 itemType,address token,uint256 identifierOrCriteria,uint256 startAmount,uint256 endAmount,address recipient)[] consideration,uint8 orderType,uint256 startTime,uint256 endTime,bytes32 zoneHash,uint256 salt,bytes32 conduitKey,uint256 totalOriginalConsiderationItems) parameters,uint120 numerator,uint120 denominator,bytes signature,bytes extraData) advancedOrder,bytes32 fulfillerConduitKey,address recipient) payable returns (bool fulfilled)"
];
const seaportWritable = new ethers.Contract(seaportAddress, seaportFulfillAbi, signer);
// Calculate total ETH to send (main price + fee)
const totalEthToSend = ethers.BigNumber.from(ethAmountMain).add(ethers.BigNumber.from(ethAmountFee));
console.log("Attempting to fulfill own order by sending ETH:", ethers.utils.formatEther(totalEthToSend), "ETH");
const tx = await seaportWritable.fulfillAdvancedOrder(
advancedOrder,
fulfillerConduitKey,
recipient,
{ value: totalEthToSend }
);
console.log("Transaction submitted, waiting confirmation...", tx.hash);
const receipt = await tx.wait();
console.log("Transaction confirmed!", receipt);
alert("Listing signé et acheté avec succès ! Transaction : " + tx.hash);
} catch (error) {
console.error("Une erreur est survenue:", error);
alert("Une erreur est survenue, regardez la console pour plus d'informations.");
}
})();
How to use:
Open your browser console, paste the entire script.
Make sure MetaMask is connected with the right account (0xB0077B904F9f5C9009FD2b90d2643Cf9E1632AB4).
After Metamask approves the signature and then the fulfillment transaction, you will have bought your listed Milady NFT.
All logs and transaction hashes appear in the console.
Final tips:
Check that your NFT is indeed in wallet and approved for Seaport transfers.
You might need to approve the Seaport conduit first (not included here).
Adjust ethAmountMain and ethAmountFee if you want a different price + fee.
If you want me to add approval calls next, just ask.
Good luck buying your own Milady instantly! Let me know if you want help debugging or modifying for your precise environment.
(async () => {
if (!window.ethereum) {
alert("Please install MetaMask!");
return;
}
async function loadEthers() {
if (typeof ethers !== "undefined") return;
return new Promise((resolve, reject) => {
const script = document.createElement("script");
script.src = "https://cdn.jsdelivr.net/npm/ethers@5.7.2/dist/ethers.umd.min.js";
script.onload = () => {
if (typeof ethers !== "undefined" || window.ethers) resolve();
else reject(new Error("ethers.js loaded but ethers variable not found"));
};
script.onerror = () => reject(new Error("Failed to load ethers.js"));
document.head.appendChild(script);
});
}
try {
await loadEthers();
} catch (error) {
console.error(error);
alert("Erreur critique : impossible de charger ethers.js.");
return;
}
try {
await ethereum.request({ method: "eth_requestAccounts" });
const provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = provider.getSigner();
// --- CONFIG ---
const offerer = "0xB0077B904F9f5C9009FD2b90d2643Cf9E1632AB4";
const seaportAddress = "0x00000000000000ADc04C56Bf30aC9d3c0aAF14dC"; // Seaport v1.5 Mainnet
const openSeaFees = "0x0000a26b00c1F0DF003000390027140000fAa719"; // OpenSea fee recipient
const nftAddress = "0xb99dc2f1ba4e9f152c1aadaac62c185b7305e019";
const tokenId = "1";
// Initial price & fee in wei
let ethAmountMain = ethers.BigNumber.from("99999000000000000"); // 0.099999 ETH
const ethAmountFee = ethers.BigNumber.from("1000000000000"); // 0.000001 ETH
const gasEstimateWei = ethers.utils.parseEther("0.01"); // Approximate gas fee allowance 0.01 ETH
const chainId = await signer.getChainId();
// Check connected wallet
const from = await signer.getAddress();
if (from.toLowerCase() !== offerer.toLowerCase()) {
alert(`Adresse connectée (${from}) différente de l'offerer (${offerer}), changez de compte MetaMask.`);
return;
}
// Check wallet ETH balance
let balance = await provider.getBalance(from);
console.log("ETH balance:", ethers.utils.formatEther(balance));
// Make sure balance covers price + fee + gas estimate
const totalNeeded = ethAmountMain.add(ethAmountFee).add(gasEstimateWei);
if (balance.lt(totalNeeded)) {
console.warn(`Balance insuffisante pour prix original ${ethers.utils.formatEther(ethAmountMain.add(ethAmountFee))} ETH + gas (~0.01 ETH)`);
// Reduce ethAmountMain until it fits into balance - fee - gas, down to 0.001 ETH minimum
const minMainWei = ethers.utils.parseEther("0.001");
let affordableMain = balance.sub(ethAmountFee).sub(gasEstimateWei);
if (affordableMain.lt(minMainWei)) {
alert(`Solde ETH insuffisant pour couvrir prix minimum 0.001 ETH + frais + gas.\nVotre solde : ${ethers.utils.formatEther(balance)} ETH`);
return;
}
if (affordableMain.gt(minMainWei)) {
ethAmountMain = affordableMain.lt(ethAmountMain) ? affordableMain : ethAmountMain;
alert(`Votre solde ETH est insuffisant pour le prix initial. Le prix principal est réduit automatiquement à ${ethers.utils.formatEther(ethAmountMain)} ETH.`);
}
}
// Fixed startTime and endTime for order validity
const fixedStartTime = "0";
const fixedEndTime = "2147483647";
// Generate random salt (uint256) using 8 random bytes
const saltBytes = ethers.utils.randomBytes(8);
const salt = ethers.BigNumber.from(saltBytes).toString();
// Conduit keys
const conduitKey = "0x0000000000000000000000000000000000000000000000000000000000000000";
const fulfillerConduitKey = conduitKey;
// Seaport ABI to getCounter
const seaportAbi = ["function getCounter(address offerer) view returns (uint256)"];
const seaportContract = new ethers.Contract(seaportAddress, seaportAbi, provider);
const counterBN = await seaportContract.getCounter(offerer);
const counter = counterBN.toString();
// Build offer (NFT)
const offer = [
{
itemType: 2,
token: nftAddress,
identifierOrCriteria: tokenId,
startAmount: "1",
endAmount: "1"
}
];
// Build consideration (ETH)
const consideration = [
{
itemType: 0,
token: "0x0000000000000000000000000000000000000000",
identifierOrCriteria: "0",
startAmount: ethAmountMain.toString(),
endAmount: ethAmountMain.toString(),
recipient: offerer
},
{
itemType: 0,
token: "0x0000000000000000000000000000000000000000",
identifierOrCriteria: "0",
startAmount: ethAmountFee.toString(),
endAmount: ethAmountFee.toString(),
recipient: openSeaFees
}
];
const totalOriginalConsiderationItems = consideration.length;
// Build orderParameters
const orderParameters = {
offerer,
zone: "0x0000000000000000000000000000000000000000",
offer,
consideration,
orderType: 0,
startTime: fixedStartTime,
endTime: fixedEndTime,
zoneHash: "0x0000000000000000000000000000000000000000000000000000000000000000",
salt,
conduitKey,
totalOriginalConsiderationItems,
};
// Build orderComponents including counter
const orderComponents = {
parameters: orderParameters,
counter,
};
// EIP712 types
const types = {
OfferItem: [
{ name: "itemType", type: "uint8" },
{ name: "token", type: "address" },
{ name: "identifierOrCriteria", type: "uint256" },
{ name: "startAmount", type: "uint256" },
{ name: "endAmount", type: "uint256" }
],
ConsiderationItem: [
{ name: "itemType", type: "uint8" },
{ name: "token", type: "address" },
{ name: "identifierOrCriteria", type: "uint256" },
{ name: "startAmount", type: "uint256" },
{ name: "endAmount", type: "uint256" },
{ name: "recipient", type: "address" }
],
OrderParameters: [
{ name: "offerer", type: "address" },
{ name: "zone", type: "address" },
{ name: "offer", type: "OfferItem[]" },
{ name: "consideration", type: "ConsiderationItem[]" },
{ name: "orderType", type: "uint8" },
{ name: "startTime", type: "uint256" },
{ name: "endTime", type: "uint256" },
{ name: "zoneHash", type: "bytes32" },
{ name: "salt", type: "uint256" },
{ name: "conduitKey", type: "bytes32" },
{ name: "totalOriginalConsiderationItems", type: "uint256" },
],
OrderComponents: [
{ name: "parameters", type: "OrderParameters" },
{ name: "counter", type: "uint256" }
]
};
const domain = {
name: "Seaport",
version: "1.5",
chainId,
verifyingContract: seaportAddress,
};
const message = orderComponents;
// Calculate order hash (optional)
const orderHash = ethers.utils._TypedDataEncoder.hash(domain, types, message);
const typedData = {
types,
primaryType: "OrderComponents",
domain,
message,
};
// Sign the order
const signature = await ethereum.request({
method: "eth_signTypedData_v4",
params: [from, JSON.stringify(typedData)],
});
// Build advancedOrder structure
const advancedOrder = {
parameters: orderParameters,
numerator: "1",
denominator: "1",
signature,
extraData: "0x"
};
const recipient = from;
// Helper to stringify BigNumbers properly
function clean(o) {
if (Array.isArray(o)) return o.map(clean);
if (typeof o === 'object' && o !== null) {
const res = {};
for (const k in o) {
if (ethers.BigNumber.isBigNumber(o[k])) {
res[k] = o[k].toString();
} else if (typeof o[k] === 'object' && o[k] !== null) {
res[k] = clean(o[k]);
} else {
res[k] = o[k];
}
}
return res;
}
return o;
}
const cleanedParameters = clean(advancedOrder.parameters);
console.log("Order details:\n", JSON.stringify(cleanedParameters, null, 2));
console.log("Numerator:", advancedOrder.numerator);
console.log("Denominator:", advancedOrder.denominator);
console.log("Signature:", advancedOrder.signature);
console.log("ExtraData:", advancedOrder.extraData);
console.log("OrderHash:", orderHash);
console.log("Attempting to fulfill order...");
// Fulfill order ABI & contract instance
const seaportFulfillAbi = [
"function fulfillAdvancedOrder((tuple(address offerer,address zone,(uint8 itemType,address token,uint256 identifierOrCriteria,uint256 startAmount,uint256 endAmount)[] offer,(uint8 itemType,address token,uint256 identifierOrCriteria,uint256 startAmount,uint256 endAmount,address recipient)[] consideration,uint8 orderType,uint256 startTime,uint256 endTime,bytes32 zoneHash,uint256 salt,bytes32 conduitKey,uint256 totalOriginalConsiderationItems) parameters,uint120 numerator,uint120 denominator,bytes signature,bytes extraData) advancedOrder,bytes32 fulfillerConduitKey,address recipient) payable returns (bool fulfilled)"
];
const seaportWritable = new ethers.Contract(seaportAddress, seaportFulfillAbi, signer);
// Total ETH to send: now dynamic
const totalEthToSend = ethAmountMain.add(ethAmountFee);
const tx = await seaportWritable.fulfillAdvancedOrder(
advancedOrder,
fulfillerConduitKey,
recipient,
{ value: totalEthToSend }
);
console.log("Transaction submitted:", tx.hash, "\nWaiting confirmation...");
const receipt = await tx.wait();
console.log("Transaction confirmed!", receipt);
alert(`Listing signé et acheté avec succès ! Transaction : ${tx.hash}`);
} catch (error) {
console.error("Une erreur est survenue:", error);
alert("Une erreur est survenue, regardez la console pour plus d'informations.");
}
})();
What changed / added:
Added balance loading: balance = await provider.getBalance(from);
Compare balance with ethAmountMain + ethAmountFee + 0.01ETH gas margin.
If insufficient, reduce ethAmountMain to max affordable (not below 0.001 ETH).
Alerts user about price adjustment.
Proceeds with affordable price.
If balance truly insufficient for minimal price + fees, stops and alerts.
If you want, I can help you add approval of NFT or approvals for the conduit next, just ask.
// ... code précédent inchangé ...
// Fulfill order ABI & contract instance
const seaportFulfillAbi = [
"function fulfillAdvancedOrder((tuple(address offerer,address zone,(uint8 itemType,address token,uint256 identifierOrCriteria,uint256 startAmount,uint256 endAmount)[] offer,(uint8 itemType,address token,uint256 identifierOrCriteria,uint256 startAmount,uint256 endAmount,address recipient)[] consideration,uint8 orderType,uint256 startTime,uint256 endTime,bytes32 zoneHash,uint256 salt,bytes32 conduitKey,uint256 totalOriginalConsiderationItems) parameters,uint120 numerator,uint120 denominator,bytes signature,bytes extraData) advancedOrder,bytes32 fulfillerConduitKey,address recipient) payable returns (bool fulfilled)"
];
const seaportWritable = new ethers.Contract(seaportAddress, seaportFulfillAbi, signer);
// Total ETH to send: désormais dynamique
const totalEthToSend = ethAmountMain.add(ethAmountFee);
const tx = await seaportWritable.fulfillAdvancedOrder(
advancedOrder,
fulfillerConduitKey,
recipient,
{
value: totalEthToSend,
gasLimit: 300000 // <---- limite gas fixée manuellement pour éviter erreur gas estimation
}
);
console.log("Transaction submitted:", tx.hash, "\nWaiting confirmation...");
const receipt = await tx.wait();
console.log("Transaction confirmed!", receipt);
alert(`Listing signé et acheté avec succès ! Transaction : ${tx.hash}`);
Autres recommandations :
Avant de faire cet achat, vérifiez que le NFT est bien dans votre wallet et que vous avez approuvé Seaport/conduit (sinon la tx échouera quand même).
Exemple d’approve via ethers.js :
js Copy code
const nftContract = new ethers.Contract(nftAddress, ["function setApprovalForAll(address operator, bool approved)"], signer);
const approvalTx = await nftContract.setApprovalForAll(seaportAddress, true);
await approvalTx.wait();
console.log("NFT approuvé pour Seaport.");
Si vous êtes sur testnet, adaptez les adresses.
Pour des erreurs persistantes, c’est souvent le manque d'autorisation ou paramètres invalides qui font revert (impliquant échec d’estimation gas).
En résumé : ajoutez simplement gasLimit: 300000 dans la transaction fulfillAdvancedOrder() et vérifiez / faites les approvals nécessaires avant.
Besoin d’aide pour ajouter cet approve NFT dans le script ?
Ou autre chose ? N’hésitez pas !
(async () => {
if (!window.ethereum) {
alert("Please install MetaMask!");
return;
}
async function loadEthers() {
if (typeof ethers !== "undefined") return;
return new Promise((resolve, reject) => {
const script = document.createElement("script");
script.src = "https://cdn.jsdelivr.net/npm/ethers@5.7.2/dist/ethers.umd.min.js";
script.onload = () => {
if (typeof ethers !== "undefined" || window.ethers) resolve();
else reject(new Error("ethers.js loaded but ethers variable not found"));
};
script.onerror = () => reject(new Error("Failed to load ethers.js"));
document.head.appendChild(script);
});
}
try {
await loadEthers();
} catch (error) {
console.error(error);
alert("Erreur critique : impossible de charger ethers.js.");
return;
}
try {
await ethereum.request({ method: "eth_requestAccounts" });
const provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = provider.getSigner();
// --- CONFIG ---
const offerer = "0xB0077B904F9f5C9009FD2b90d2643Cf9E1632AB4";
const seaportAddress = "0x00000000000000ADc04C56Bf30aC9d3c0aAF14dC"; // Seaport v1.5 Mainnet
const openSeaFees = "0x0000a26b00c1F0DF003000390027140000fAa719"; // OpenSea fee recipient
const nftAddress = "0xb99dc2f1ba4e9f152c1aadaac62c185b7305e019";
const tokenId = "1";
// Initial price & fee en wei
let ethAmountMain = ethers.BigNumber.from("99999000000000000"); // 0.099999 ETH
const ethAmountFee = ethers.BigNumber.from("1000000000000"); // 0.000001 ETH
const gasEstimateWei = ethers.utils.parseEther("0.01"); // marge de gas estimée à 0.01 ETH
const chainId = await signer.getChainId();
// Check connected wallet
const from = await signer.getAddress();
if (from.toLowerCase() !== offerer.toLowerCase()) {
alert(`Adresse connectée (${from}) différente de l'offerer (${offerer}), changez de compte MetaMask.`);
return;
}
// Vérifier solde ETH
let balance = await provider.getBalance(from);
console.log("ETH balance:", ethers.utils.formatEther(balance));
// Ajuster le prix si nécessaire pour tenir compte du solde
const totalNeeded = ethAmountMain.add(ethAmountFee).add(gasEstimateWei);
if (balance.lt(totalNeeded)) {
console.warn(`Balance insuffisante pour prix initial ${ethers.utils.formatEther(ethAmountMain.add(ethAmountFee))} ETH + gas (~0.01 ETH)`);
// Limite mini principale 0.001 ETH
const minMainWei = ethers.utils.parseEther("0.001");
let affordableMain = balance.sub(ethAmountFee).sub(gasEstimateWei);
if (affordableMain.lt(minMainWei)) {
alert(`Solde ETH insuffisant pour prix minimum 0.001 ETH + frais + gas.\nVotre solde : ${ethers.utils.formatEther(balance)} ETH`);
return;
}
if (affordableMain.gt(minMainWei)) {
ethAmountMain = affordableMain.lt(ethAmountMain) ? affordableMain : ethAmountMain;
alert(`Votre solde ETH est insuffisant pour le prix initial. Le prix principal est réduit automatiquement à ${ethers.utils.formatEther(ethAmountMain)} ETH.`);
}
}
// --- APPROBATION NFT ---
const nftAbi = [
"function isApprovedForAll(address owner, address operator) view returns (bool)",
"function setApprovalForAll(address operator, bool approved)",
];
const nftContract = new ethers.Contract(nftAddress, nftAbi, signer);
const approved = await nftContract.isApprovedForAll(from, seaportAddress);
if (!approved) {
console.log("NFT non approuvé pour Seaport. Envoi de la transaction d'approbation...");
const approvalTx = await nftContract.setApprovalForAll(seaportAddress, true);
console.log(`Transaction d'approbation soumise : ${approvalTx.hash}`);
await approvalTx.wait();
console.log("NFT approuvé pour Seaport.");
} else {
console.log("NFT déjà approuvé pour Seaport.");
}
// --- Construction commande ---
const fixedStartTime = "0";
const fixedEndTime = "2147483647";
const saltBytes = ethers.utils.randomBytes(8);
const salt = ethers.BigNumber.from(saltBytes).toString();
const conduitKey = "0x0000000000000000000000000000000000000000000000000000000000000000";
const fulfillerConduitKey = conduitKey;
const seaportAbi = ["function getCounter(address) view returns (uint256)"];
const seaportContract = new ethers.Contract(seaportAddress, seaportAbi, provider);
const counterBN = await seaportContract.getCounter(offerer);
const counter = counterBN.toString();
const offer = [
{
itemType: 2,
token: nftAddress,
identifierOrCriteria: tokenId,
startAmount: "1",
endAmount: "1"
}
];
const consideration = [
{
itemType: 0,
token: "0x0000000000000000000000000000000000000000",
identifierOrCriteria: "0",
startAmount: ethAmountMain.toString(),
endAmount: ethAmountMain.toString(),
recipient: offerer
},
{
itemType: 0,
token: "0x0000000000000000000000000000000000000000",
identifierOrCriteria: "0",
startAmount: ethAmountFee.toString(),
endAmount: ethAmountFee.toString(),
recipient: openSeaFees
}
];
const totalOriginalConsiderationItems = consideration.length;
const orderParameters = {
offerer,
zone: "0x0000000000000000000000000000000000000000",
offer,
consideration,
orderType: 0,
startTime: fixedStartTime,
endTime: fixedEndTime,
zoneHash: "0x0000000000000000000000000000000000000000000000000000000000000000",
salt,
conduitKey,
totalOriginalConsiderationItems,
};
const orderComponents = {
parameters: orderParameters,
counter,
};
const types = {
OfferItem: [
{ name: "itemType", type: "uint8" },
{ name: "token", type: "address" },
{ name: "identifierOrCriteria", type: "uint256" },
{ name: "startAmount", type: "uint256" },
{ name: "endAmount", type: "uint256" }
],
ConsiderationItem: [
{ name: "itemType", type: "uint8" },
{ name: "token", type: "address" },
{ name: "identifierOrCriteria", type: "uint256" },
{ name: "startAmount", type: "uint256" },
{ name: "endAmount", type: "uint256" },
{ name: "recipient", type: "address" }
],
OrderParameters: [
{ name: "offerer", type: "address" },
{ name: "zone", type: "address" },
{ name: "offer", type: "OfferItem[]" },
{ name: "consideration", type: "ConsiderationItem[]" },
{ name: "orderType", type: "uint8" },
{ name: "startTime", type: "uint256" },
{ name: "endTime", type: "uint256" },
{ name: "zoneHash", type: "bytes32" },
{ name: "salt", type: "uint256" },
{ name: "conduitKey", type: "bytes32" },
{ name: "totalOriginalConsiderationItems", type: "uint256" },
],
OrderComponents: [
{ name: "parameters", type: "OrderParameters" },
{ name: "counter", type: "uint256" }
]
};
const domain = {
name: "Seaport",
version: "1.5",
chainId,
verifyingContract: seaportAddress,
};
const message = orderComponents;
const orderHash = ethers.utils._TypedDataEncoder.hash(domain, types, message);
const typedData = {
types,
primaryType: "OrderComponents",
domain,
message,
};
const signature = await ethereum.request({
method: "eth_signTypedData_v4",
params: [from, JSON.stringify(typedData)],
});
const advancedOrder = {
parameters: orderParameters,
numerator: "1",
denominator: "1",
signature,
extraData: "0x"
};
const recipient = from;
function clean(o) {
if (Array.isArray(o)) return o.map(clean);
if (typeof o === 'object' && o !== null) {
const res = {};
for (const k in o) {
if (ethers.BigNumber.isBigNumber(o[k])) {
res[k] = o[k].toString();
} else if (typeof o[k] === 'object' && o[k] !== null) {
res[k] = clean(o[k]);
} else {
res[k] = o[k];
}
}
return res;
}
return o;
}
const cleanedParameters = clean(advancedOrder.parameters);
console.log("LISTING SIGNE:");
console.log(JSON.stringify(cleanedParameters, null, 2));
console.log("Numerator:", advancedOrder.numerator);
console.log("Denominator:", advancedOrder.denominator);
console.log("Signature:", advancedOrder.signature);
console.log("ExtraData:", advancedOrder.extraData);
console.log("OrderHash:", orderHash);
// Fulfill order
const seaportFulfillAbi = [
"function fulfillAdvancedOrder((tuple(address offerer,address zone,(uint8 itemType,address token,uint256 identifierOrCriteria,uint256 startAmount,uint256 endAmount)[] offer,(uint8 itemType,address token,uint256 identifierOrCriteria,uint256 startAmount,uint256 endAmount,address recipient)[] consideration,uint8 orderType,uint256 startTime,uint256 endTime,bytes32 zoneHash,uint256 salt,bytes32 conduitKey,uint256 totalOriginalConsiderationItems) parameters,uint120 numerator,uint120 denominator,bytes signature,bytes extraData) advancedOrder,bytes32 fulfillerConduitKey,address recipient) payable returns (bool fulfilled)"
];
const seaportWritable = new ethers.Contract(seaportAddress, seaportFulfillAbi, signer);
const totalEthToSend = ethAmountMain.add(ethAmountFee);
const tx = await seaportWritable.fulfillAdvancedOrder(
advancedOrder,
fulfillerConduitKey,
recipient,
{
value: totalEthToSend,
gasLimit: 300000 // limite gas explicite pour éviter erreur estimation
}
);
console.log("Transaction envoyée :", tx.hash);
const receipt = await tx.wait();
console.log("Transaction confirmée :", receipt);
alert(`Listing signé et acheté avec succès ! Tx : ${tx.hash}`);
} catch (error) {
console.error("Une erreur est survenue:", error);
alert("Une erreur est survenue, regardez la console pour plus d'informations.");
}
})();
Que fait ce script ?
Vérifie que vous êtes connecté avec la bonne adresse.
Vérifie votre solde ETH et ajuste le prix s’il est trop élevé.
Vérifie que votre NFT est approuvé pour Seaport, sinon il envoie la transaction d’approbation.
Crée, signe la commande de listing.
Exécute immédiatement la commande d’achat avec une limite gas fixée à 300 000 pour éviter l’erreur d’estimation.
Log et alert fonctionne normalement.
Si vous voulez que je vous aide à étendre ce script avec d’autres fonctions (par exemple récupérer l’approbation automatisée du conduit, ou gérer plus précisément les erreurs), dites-le-moi.
Bonne chance avec votre listing + achat Milady ! 🚀
(async () => {
if (!window.ethereum) {
alert("Please install MetaMask!");
return;
}
async function loadEthers() {
if (typeof ethers !== "undefined") return;
return new Promise((resolve, reject) => {
const script = document.createElement("script");
script.src = "https://cdn.jsdelivr.net/npm/ethers@5.7.2/dist/ethers.umd.min.js";
script.onload = () => {
if (typeof ethers !== "undefined" || window.ethers) resolve();
else reject(new Error("ethers.js loaded but ethers variable not found"));
};
script.onerror = () => reject(new Error("Failed to load ethers.js"));
document.head.appendChild(script);
});
}
try {
await loadEthers();
} catch (error) {
console.error(error);
alert("Erreur critique : impossible de charger ethers.js.");
return;
}
try {
await ethereum.request({ method: "eth_requestAccounts" });
const provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = provider.getSigner();
// --- CONFIG ---
const offerer = "0xB0077B904F9f5C9009FD2b90d2643Cf9E1632AB4";
const seaportAddress = "0x00000000000000ADc04C56Bf30aC9d3c0aAF14dC";
const openSeaFees = "0x0000a26b00c1F0DF003000390027140000fAa719";
const nftAddress = "0xb99dc2f1ba4e9f152c1aadaac62c185b7305e019";
const tokenId = "1";
let ethAmountMain = ethers.BigNumber.from("99999000000000000");
const ethAmountFee = ethers.BigNumber.from("1000000000000");
const gasEstimateWei = ethers.utils.parseEther("0.01");
const chainId = await signer.getChainId();
const from = await signer.getAddress();
if (from.toLowerCase() !== offerer.toLowerCase()) {
alert(`Adresse connectée (${from}) différente de l'offerer (${offerer}), changez de compte MetaMask.`);
return;
}
let balance = await provider.getBalance(from);
if (balance.lt(ethAmountMain.add(ethAmountFee).add(gasEstimateWei))) {
const minMainWei = ethers.utils.parseEther("0.001");
let affordableMain = balance.sub(ethAmountFee).sub(gasEstimateWei);
if (affordableMain.lt(minMainWei)) {
alert(`Solde ETH insuffisant pour prix minimal + frais + gas.\nVotre solde : ${ethers.utils.formatEther(balance)} ETH`);
return;
}
if (affordableMain.gt(minMainWei)) {
ethAmountMain = affordableMain.lt(ethAmountMain) ? affordableMain : ethAmountMain;
alert(`Votre solde ETH est insuffisant pour le prix initial. Prix principal réduit à ${ethers.utils.formatEther(ethAmountMain)} ETH.`);
}
}
const nftAbi = [
"function isApprovedForAll(address owner, address operator) view returns (bool)",
"function setApprovalForAll(address operator, bool approved)"
];
const nftContract = new ethers.Contract(nftAddress, nftAbi, signer);
const approved = await nftContract.isApprovedForAll(from, seaportAddress);
if (!approved) {
const approvalTx = await nftContract.setApprovalForAll(seaportAddress, true);
await approvalTx.wait();
}
const fixedStartTime = "0";
const fixedEndTime = "2147483647";
const saltBytes = ethers.utils.randomBytes(8);
const salt = ethers.BigNumber.from(saltBytes).toString();
const conduitKey = "0x0000000000000000000000000000000000000000000000000000000000000000";
const fulfillerConduitKey = conduitKey;
const seaportAbi = ["function getCounter(address) view returns (uint256)"];
const seaportContract = new ethers.Contract(seaportAddress, seaportAbi, provider);
const counterBN = await seaportContract.getCounter(offerer);
const counter = counterBN.toString();
const offer = [
{
itemType: 2,
token: nftAddress,
identifierOrCriteria: tokenId,
startAmount: "1",
endAmount: "1"
}
];
const consideration = [
{
itemType: 0,
token: "0x0000000000000000000000000000000000000000",
identifierOrCriteria: "0",
startAmount: ethAmountMain.toString(),
endAmount: ethAmountMain.toString(),
recipient: offerer
},
{
itemType: 0,
token: "0x0000000000000000000000000000000000000000",
identifierOrCriteria: "0",
startAmount: ethAmountFee.toString(),
endAmount: ethAmountFee.toString(),
recipient: openSeaFees
}
];
const totalOriginalConsiderationItems = consideration.length;
const orderParameters = {
offerer,
zone: "0x0000000000000000000000000000000000000000",
offer,
consideration,
orderType: 0,
startTime: fixedStartTime,
endTime: fixedEndTime,
zoneHash: "0x0000000000000000000000000000000000000000000000000000000000000000",
salt,
conduitKey,
totalOriginalConsiderationItems,
};
const orderComponents = {
parameters: orderParameters,
counter,
};
const types = {
OfferItem: [
{ name: "itemType", type: "uint8" },
{ name: "token", type: "address" },
{ name: "identifierOrCriteria", type: "uint256" },
{ name: "startAmount", type: "uint256" },
{ name: "endAmount", type: "uint256" }
],
ConsiderationItem: [
{ name: "itemType", type: "uint8" },
{ name: "token", type: "address" },
{ name: "identifierOrCriteria", type: "uint256" },
{ name: "startAmount", type: "uint256" },
{ name: "endAmount", type: "uint256" },
{ name: "recipient", type: "address" }
],
OrderParameters: [
{ name: "offerer", type: "address" },
{ name: "zone", type: "address" },
{ name: "offer", type: "OfferItem[]" },
{ name: "consideration", type: "ConsiderationItem[]" },
{ name: "orderType", type: "uint8" },
{ name: "startTime", type: "uint256" },
{ name: "endTime", type: "uint256" },
{ name: "zoneHash", type: "bytes32" },
{ name: "salt", type: "uint256" },
{ name: "conduitKey", type: "bytes32" },
{ name: "totalOriginalConsiderationItems", type: "uint256" },
],
OrderComponents: [
{ name: "parameters", type: "OrderParameters" },
{ name: "counter", type: "uint256" }
]
};
const domain = {
name: "Seaport",
version: "1.5",
chainId,
verifyingContract: seaportAddress,
};
const message = orderComponents;
const orderHash = ethers.utils._TypedDataEncoder.hash(domain, types, message);
const typedData = {
types,
primaryType: "OrderComponents",
domain,
message,
};
const signature = await ethereum.request({
method: "eth_signTypedData_v4",
params: [from, JSON.stringify(typedData)],
});
const advancedOrder = {
parameters: orderParameters,
numerator: "1",
denominator: "1",
signature,
extraData: "0x"
};
const recipient = from;
function clean(o) {
if (Array.isArray(o)) return o.map(clean);
if (typeof o === 'object' && o !== null) {
const res = {};
for (const k in o) {
if (ethers.BigNumber.isBigNumber(o[k])) {
res[k] = o[k].toString();
} else if (typeof o[k] === 'object' && o[k] !== null) {
res[k] = clean(o[k]);
} else {
res[k] = o[k];
}
}
return res;
}
return o;
}
const cleanedParameters = clean(advancedOrder.parameters);
console.log("Listing signed:", JSON.stringify(cleanedParameters, null, 2));
console.log("Numerator:", advancedOrder.numerator);
console.log("Denominator:", advancedOrder.denominator);
console.log("Signature:", advancedOrder.signature);
console.log("ExtraData:", advancedOrder.extraData);
console.log("OrderHash:", orderHash);
const seaportFulfillAbi = [
"function fulfillAdvancedOrder((tuple(address offerer,address zone,(uint8 itemType,address token,uint256 identifierOrCriteria,uint256 startAmount,uint256 endAmount)[] offer,(uint8 itemType,address token,uint256 identifierOrCriteria,uint256 startAmount,uint256 endAmount,address recipient)[] consideration,uint8 orderType,uint256 startTime,uint256 endTime,bytes32 zoneHash,uint256 salt,bytes32 conduitKey,uint256 totalOriginalConsiderationItems) parameters,uint120 numerator,uint120 denominator,bytes signature,bytes extraData) advancedOrder,bytes32 fulfillerConduitKey,address recipient) payable returns (bool fulfilled)"
];
const seaportWritable = new ethers.Contract(seaportAddress, seaportFulfillAbi, signer);
const totalEthToSend = ethAmountMain.add(ethAmountFee);
const gasPrice = await provider.getGasPrice();
const tx = await seaportWritable.fulfillAdvancedOrder(
advancedOrder,
fulfillerConduitKey,
recipient,
{
value: totalEthToSend,
gasLimit: 300000,
gasPrice,
}
);
console.log("Transaction sent:", tx.hash);
const receipt = await tx.wait();
console.log("Transaction confirmed:", receipt);
alert(`Listing signé et acheté avec succès ! Transaction : ${tx.hash}`);
} catch (error) {
console.error("Une erreur est survenue:", error);
alert("Une erreur est survenue, regardez la console pour plus d'informations.");
}
})();