@elizaos/plugin-story
Version:
Story Protocol plugin for elizaOS - enables IP registration, licensing, and terms attachment on Story Protocol
1,497 lines (1,448 loc) • 300 kB
JavaScript
import {
secp256k1,
sha256
} from "./chunk-BY7PMZNZ.js";
import {
AbiDecodingDataSizeTooSmallError,
AbiDecodingZeroDataError,
AbiEventNotFoundError,
AbiEventSignatureEmptyTopicsError,
AbiEventSignatureNotFoundError,
AtomicReadyWalletRejectedUpgradeError,
AtomicityNotSupportedError,
BaseError,
BaseError2,
BundleTooLargeError,
BytesSizeMismatchError,
CallExecutionError,
ChainDisconnectedError,
ChainMismatchError,
ChainNotFoundError,
ContractFunctionExecutionError,
ContractFunctionRevertedError,
ContractFunctionZeroDataError,
DecodeLogDataMismatch,
DecodeLogTopicsMismatch,
DuplicateIdError,
FeeCapTooHighError,
HttpRequestError,
IntegerOutOfRangeError,
InternalRpcError,
InvalidAddressError,
InvalidChainIdError,
InvalidInputRpcError,
InvalidLegacyVError,
InvalidParamsRpcError,
InvalidRequestRpcError,
InvalidSerializableTransactionError,
InvalidStorageKeySizeError,
JsonRpcVersionUnsupportedError,
LimitExceededRpcError,
LruMap,
MethodNotFoundRpcError,
MethodNotSupportedRpcError,
ParseRpcError,
PositionOutOfBoundsError,
ProviderDisconnectedError,
RawContractError,
ResourceNotFoundRpcError,
ResourceUnavailableRpcError,
RpcRequestError,
SwitchChainError,
TimeoutError,
TipAboveFeeCapError,
TransactionExecutionError,
TransactionNotFoundError,
TransactionReceiptNotFoundError,
TransactionRejectedRpcError,
UnauthorizedProviderError,
UnknownBundleIdError,
UnknownNodeError,
UnknownRpcError,
UnsupportedChainIdError,
UnsupportedNonOptionalCapabilityError,
UnsupportedProviderMethodError,
UserRejectedRequestError,
WaitForTransactionReceiptTimeoutError,
addressResolverAbi,
assertRequest,
bytesRegex,
bytesToHex,
call,
checksumAddress,
concat,
concat2,
concatHex,
createBatchScheduler,
createCursor,
decodeAbiParameters,
decodeFunctionResult,
deploylessCallViaBytecodeBytecode,
encodeAbiParameters,
encodeDeployData,
encodeFunctionData,
extract,
formatAbiItem,
formatEther,
formatGwei,
formatTransactionRequest,
formatUnits,
from,
fromBoolean,
fromBytes,
fromNumber,
fromString,
fromString2,
getAbiItem,
getAddress,
getCallError,
getChainContractAddress,
getNodeError,
hexToBigInt,
hexToBool,
hexToBytes,
hexToNumber,
integerRegex,
isAddress,
isAddressEqual,
isHex,
keccak256,
keccak_256,
localBatchGatewayUrl,
maxUint256,
multicall3Abi,
numberToHex,
padLeft,
padRight,
panicReasons,
parseAccount,
prettyPrint,
serializeStateOverride,
size,
size2,
slice,
slice2,
sliceHex,
stringToBytes,
stringToHex,
stringify,
textResolverAbi,
toBytes,
toEventSelector,
toHex,
toRpc,
trim,
universalResolverResolveAbi,
universalResolverReverseAbi,
universalSignatureValidatorAbi,
universalSignatureValidatorByteCode,
validate,
withResolvers
} from "./chunk-NAW7NVIH.js";
import "./chunk-C32RXCHU.js";
import "./chunk-PR4QN5HX.js";
// src/actions/registerIP.ts
import {
composePromptFromState,
elizaLogger,
parseKeyValueXml,
ModelType
} from "@elizaos/core";
import pinataSDK from "@pinata/sdk";
import { createHash } from "node:crypto";
// src/functions/uploadJSONToIPFS.ts
async function uploadJSONToIPFS(pinata, jsonMetadata) {
const { IpfsHash } = await pinata.pinJSONToIPFS(jsonMetadata);
return IpfsHash;
}
// node_modules/viem/_esm/utils/getAction.js
function getAction(client, actionFn, name) {
const action_implicit = client[actionFn.name];
if (typeof action_implicit === "function")
return action_implicit;
const action_explicit = client[name];
if (typeof action_explicit === "function")
return action_explicit;
return (params) => actionFn(client, params);
}
// node_modules/viem/_esm/errors/log.js
var FilterTypeNotSupportedError = class extends BaseError {
constructor(type) {
super(`Filter type "${type}" is not supported.`, {
name: "FilterTypeNotSupportedError"
});
}
};
// node_modules/viem/_esm/utils/abi/encodeEventTopics.js
var docsPath = "/docs/contract/encodeEventTopics";
function encodeEventTopics(parameters) {
const { abi: abi2, eventName, args } = parameters;
let abiItem = abi2[0];
if (eventName) {
const item = getAbiItem({ abi: abi2, name: eventName });
if (!item)
throw new AbiEventNotFoundError(eventName, { docsPath });
abiItem = item;
}
if (abiItem.type !== "event")
throw new AbiEventNotFoundError(void 0, { docsPath });
const definition = formatAbiItem(abiItem);
const signature = toEventSelector(definition);
let topics = [];
if (args && "inputs" in abiItem) {
const indexedInputs = abiItem.inputs?.filter((param) => "indexed" in param && param.indexed);
const args_ = Array.isArray(args) ? args : Object.values(args).length > 0 ? indexedInputs?.map((x) => args[x.name]) ?? [] : [];
if (args_.length > 0) {
topics = indexedInputs?.map((param, i) => {
if (Array.isArray(args_[i]))
return args_[i].map((_, j) => encodeArg({ param, value: args_[i][j] }));
return typeof args_[i] !== "undefined" && args_[i] !== null ? encodeArg({ param, value: args_[i] }) : null;
}) ?? [];
}
}
return [signature, ...topics];
}
function encodeArg({ param, value }) {
if (param.type === "string" || param.type === "bytes")
return keccak256(toBytes(value));
if (param.type === "tuple" || param.type.match(/^(.*)\[(\d+)?\]$/))
throw new FilterTypeNotSupportedError(param.type);
return encodeAbiParameters([param], [value]);
}
// node_modules/viem/_esm/utils/filters/createFilterRequestScope.js
function createFilterRequestScope(client, { method }) {
const requestMap = {};
if (client.transport.type === "fallback")
client.transport.onResponse?.(({ method: method_, response: id, status, transport }) => {
if (status === "success" && method === method_)
requestMap[id] = transport.request;
});
return (id) => requestMap[id] || client.request;
}
// node_modules/viem/_esm/actions/public/createContractEventFilter.js
async function createContractEventFilter(client, parameters) {
const { address, abi: abi2, args, eventName, fromBlock, strict, toBlock } = parameters;
const getRequest = createFilterRequestScope(client, {
method: "eth_newFilter"
});
const topics = eventName ? encodeEventTopics({
abi: abi2,
args,
eventName
}) : void 0;
const id = await client.request({
method: "eth_newFilter",
params: [
{
address,
fromBlock: typeof fromBlock === "bigint" ? numberToHex(fromBlock) : fromBlock,
toBlock: typeof toBlock === "bigint" ? numberToHex(toBlock) : toBlock,
topics
}
]
});
return {
abi: abi2,
args,
eventName,
id,
request: getRequest(id),
strict: Boolean(strict),
type: "event"
};
}
// node_modules/viem/_esm/utils/errors/getContractError.js
var EXECUTION_REVERTED_ERROR_CODE = 3;
function getContractError(err, { abi: abi2, address, args, docsPath: docsPath3, functionName, sender }) {
const error = err instanceof RawContractError ? err : err instanceof BaseError ? err.walk((err2) => "data" in err2) || err.walk() : {};
const { code, data, details, message, shortMessage } = error;
const cause = (() => {
if (err instanceof AbiDecodingZeroDataError)
return new ContractFunctionZeroDataError({ functionName });
if ([EXECUTION_REVERTED_ERROR_CODE, InternalRpcError.code].includes(code) && (data || details || message || shortMessage)) {
return new ContractFunctionRevertedError({
abi: abi2,
data: typeof data === "object" ? data.data : data,
functionName,
message: error instanceof RpcRequestError ? details : shortMessage ?? message
});
}
return err;
})();
return new ContractFunctionExecutionError(cause, {
abi: abi2,
args,
contractAddress: address,
docsPath: docsPath3,
functionName,
sender
});
}
// node_modules/viem/_esm/accounts/utils/publicKeyToAddress.js
function publicKeyToAddress(publicKey) {
const address = keccak256(`0x${publicKey.substring(4)}`).substring(26);
return checksumAddress(`0x${address}`);
}
// node_modules/viem/_esm/utils/signature/recoverPublicKey.js
async function recoverPublicKey({ hash, signature }) {
const hashHex = isHex(hash) ? hash : toHex(hash);
const { secp256k1: secp256k12 } = await import("./secp256k1-6QD6HAWI.js");
const signature_ = (() => {
if (typeof signature === "object" && "r" in signature && "s" in signature) {
const { r, s, v, yParity } = signature;
const yParityOrV2 = Number(yParity ?? v);
const recoveryBit2 = toRecoveryBit(yParityOrV2);
return new secp256k12.Signature(hexToBigInt(r), hexToBigInt(s)).addRecoveryBit(recoveryBit2);
}
const signatureHex = isHex(signature) ? signature : toHex(signature);
if (size(signatureHex) !== 65)
throw new Error("invalid signature length");
const yParityOrV = hexToNumber(`0x${signatureHex.slice(130)}`);
const recoveryBit = toRecoveryBit(yParityOrV);
return secp256k12.Signature.fromCompact(signatureHex.substring(2, 130)).addRecoveryBit(recoveryBit);
})();
const publicKey = signature_.recoverPublicKey(hashHex.substring(2)).toHex(false);
return `0x${publicKey}`;
}
function toRecoveryBit(yParityOrV) {
if (yParityOrV === 0 || yParityOrV === 1)
return yParityOrV;
if (yParityOrV === 27)
return 0;
if (yParityOrV === 28)
return 1;
throw new Error("Invalid yParityOrV value");
}
// node_modules/viem/_esm/utils/signature/recoverAddress.js
async function recoverAddress({ hash, signature }) {
return publicKeyToAddress(await recoverPublicKey({ hash, signature }));
}
// node_modules/viem/_esm/utils/encoding/toRlp.js
function toRlp(bytes, to = "hex") {
const encodable = getEncodable(bytes);
const cursor = createCursor(new Uint8Array(encodable.length));
encodable.encode(cursor);
if (to === "hex")
return bytesToHex(cursor.bytes);
return cursor.bytes;
}
function getEncodable(bytes) {
if (Array.isArray(bytes))
return getEncodableList(bytes.map((x) => getEncodable(x)));
return getEncodableBytes(bytes);
}
function getEncodableList(list) {
const bodyLength = list.reduce((acc, x) => acc + x.length, 0);
const sizeOfBodyLength = getSizeOfLength(bodyLength);
const length = (() => {
if (bodyLength <= 55)
return 1 + bodyLength;
return 1 + sizeOfBodyLength + bodyLength;
})();
return {
length,
encode(cursor) {
if (bodyLength <= 55) {
cursor.pushByte(192 + bodyLength);
} else {
cursor.pushByte(192 + 55 + sizeOfBodyLength);
if (sizeOfBodyLength === 1)
cursor.pushUint8(bodyLength);
else if (sizeOfBodyLength === 2)
cursor.pushUint16(bodyLength);
else if (sizeOfBodyLength === 3)
cursor.pushUint24(bodyLength);
else
cursor.pushUint32(bodyLength);
}
for (const { encode: encode4 } of list) {
encode4(cursor);
}
}
};
}
function getEncodableBytes(bytesOrHex) {
const bytes = typeof bytesOrHex === "string" ? hexToBytes(bytesOrHex) : bytesOrHex;
const sizeOfBytesLength = getSizeOfLength(bytes.length);
const length = (() => {
if (bytes.length === 1 && bytes[0] < 128)
return 1;
if (bytes.length <= 55)
return 1 + bytes.length;
return 1 + sizeOfBytesLength + bytes.length;
})();
return {
length,
encode(cursor) {
if (bytes.length === 1 && bytes[0] < 128) {
cursor.pushBytes(bytes);
} else if (bytes.length <= 55) {
cursor.pushByte(128 + bytes.length);
cursor.pushBytes(bytes);
} else {
cursor.pushByte(128 + 55 + sizeOfBytesLength);
if (sizeOfBytesLength === 1)
cursor.pushUint8(bytes.length);
else if (sizeOfBytesLength === 2)
cursor.pushUint16(bytes.length);
else if (sizeOfBytesLength === 3)
cursor.pushUint24(bytes.length);
else
cursor.pushUint32(bytes.length);
cursor.pushBytes(bytes);
}
}
};
}
function getSizeOfLength(length) {
if (length < 2 ** 8)
return 1;
if (length < 2 ** 16)
return 2;
if (length < 2 ** 24)
return 3;
if (length < 2 ** 32)
return 4;
throw new BaseError("Length is too large.");
}
// node_modules/viem/_esm/utils/authorization/hashAuthorization.js
function hashAuthorization(parameters) {
const { chainId, nonce, to } = parameters;
const address = parameters.contractAddress ?? parameters.address;
const hash = keccak256(concatHex([
"0x05",
toRlp([
chainId ? numberToHex(chainId) : "0x",
address,
nonce ? numberToHex(nonce) : "0x"
])
]));
if (to === "bytes")
return hexToBytes(hash);
return hash;
}
// node_modules/viem/_esm/utils/authorization/recoverAuthorizationAddress.js
async function recoverAuthorizationAddress(parameters) {
const { authorization, signature } = parameters;
return recoverAddress({
hash: hashAuthorization(authorization),
signature: signature ?? authorization
});
}
// node_modules/viem/_esm/errors/estimateGas.js
var EstimateGasExecutionError = class extends BaseError {
constructor(cause, { account, docsPath: docsPath3, chain, data, gas, gasPrice, maxFeePerGas, maxPriorityFeePerGas, nonce, to, value }) {
const prettyArgs = prettyPrint({
from: account?.address,
to,
value: typeof value !== "undefined" && `${formatEther(value)} ${chain?.nativeCurrency?.symbol || "ETH"}`,
data,
gas,
gasPrice: typeof gasPrice !== "undefined" && `${formatGwei(gasPrice)} gwei`,
maxFeePerGas: typeof maxFeePerGas !== "undefined" && `${formatGwei(maxFeePerGas)} gwei`,
maxPriorityFeePerGas: typeof maxPriorityFeePerGas !== "undefined" && `${formatGwei(maxPriorityFeePerGas)} gwei`,
nonce
});
super(cause.shortMessage, {
cause,
docsPath: docsPath3,
metaMessages: [
...cause.metaMessages ? [...cause.metaMessages, " "] : [],
"Estimate Gas Arguments:",
prettyArgs
].filter(Boolean),
name: "EstimateGasExecutionError"
});
Object.defineProperty(this, "cause", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
this.cause = cause;
}
};
// node_modules/viem/_esm/utils/errors/getEstimateGasError.js
function getEstimateGasError(err, { docsPath: docsPath3, ...args }) {
const cause = (() => {
const cause2 = getNodeError(err, args);
if (cause2 instanceof UnknownNodeError)
return err;
return cause2;
})();
return new EstimateGasExecutionError(cause, {
docsPath: docsPath3,
...args
});
}
// node_modules/viem/_esm/errors/fee.js
var BaseFeeScalarError = class extends BaseError {
constructor() {
super("`baseFeeMultiplier` must be greater than 1.", {
name: "BaseFeeScalarError"
});
}
};
var Eip1559FeesNotSupportedError = class extends BaseError {
constructor() {
super("Chain does not support EIP-1559 fees.", {
name: "Eip1559FeesNotSupportedError"
});
}
};
var MaxFeePerGasTooLowError = class extends BaseError {
constructor({ maxPriorityFeePerGas }) {
super(`\`maxFeePerGas\` cannot be less than the \`maxPriorityFeePerGas\` (${formatGwei(maxPriorityFeePerGas)} gwei).`, { name: "MaxFeePerGasTooLowError" });
}
};
// node_modules/viem/_esm/errors/block.js
var BlockNotFoundError = class extends BaseError {
constructor({ blockHash, blockNumber }) {
let identifier = "Block";
if (blockHash)
identifier = `Block at hash "${blockHash}"`;
if (blockNumber)
identifier = `Block at number "${blockNumber}"`;
super(`${identifier} could not be found.`, { name: "BlockNotFoundError" });
}
};
// node_modules/viem/_esm/utils/formatters/transaction.js
var transactionType = {
"0x0": "legacy",
"0x1": "eip2930",
"0x2": "eip1559",
"0x3": "eip4844",
"0x4": "eip7702"
};
function formatTransaction(transaction) {
const transaction_ = {
...transaction,
blockHash: transaction.blockHash ? transaction.blockHash : null,
blockNumber: transaction.blockNumber ? BigInt(transaction.blockNumber) : null,
chainId: transaction.chainId ? hexToNumber(transaction.chainId) : void 0,
gas: transaction.gas ? BigInt(transaction.gas) : void 0,
gasPrice: transaction.gasPrice ? BigInt(transaction.gasPrice) : void 0,
maxFeePerBlobGas: transaction.maxFeePerBlobGas ? BigInt(transaction.maxFeePerBlobGas) : void 0,
maxFeePerGas: transaction.maxFeePerGas ? BigInt(transaction.maxFeePerGas) : void 0,
maxPriorityFeePerGas: transaction.maxPriorityFeePerGas ? BigInt(transaction.maxPriorityFeePerGas) : void 0,
nonce: transaction.nonce ? hexToNumber(transaction.nonce) : void 0,
to: transaction.to ? transaction.to : null,
transactionIndex: transaction.transactionIndex ? Number(transaction.transactionIndex) : null,
type: transaction.type ? transactionType[transaction.type] : void 0,
typeHex: transaction.type ? transaction.type : void 0,
value: transaction.value ? BigInt(transaction.value) : void 0,
v: transaction.v ? BigInt(transaction.v) : void 0
};
if (transaction.authorizationList)
transaction_.authorizationList = formatAuthorizationList(transaction.authorizationList);
transaction_.yParity = (() => {
if (transaction.yParity)
return Number(transaction.yParity);
if (typeof transaction_.v === "bigint") {
if (transaction_.v === 0n || transaction_.v === 27n)
return 0;
if (transaction_.v === 1n || transaction_.v === 28n)
return 1;
if (transaction_.v >= 35n)
return transaction_.v % 2n === 0n ? 1 : 0;
}
return void 0;
})();
if (transaction_.type === "legacy") {
delete transaction_.accessList;
delete transaction_.maxFeePerBlobGas;
delete transaction_.maxFeePerGas;
delete transaction_.maxPriorityFeePerGas;
delete transaction_.yParity;
}
if (transaction_.type === "eip2930") {
delete transaction_.maxFeePerBlobGas;
delete transaction_.maxFeePerGas;
delete transaction_.maxPriorityFeePerGas;
}
if (transaction_.type === "eip1559") {
delete transaction_.maxFeePerBlobGas;
}
return transaction_;
}
function formatAuthorizationList(authorizationList) {
return authorizationList.map((authorization) => ({
address: authorization.address,
chainId: Number(authorization.chainId),
nonce: Number(authorization.nonce),
r: authorization.r,
s: authorization.s,
yParity: Number(authorization.yParity)
}));
}
// node_modules/viem/_esm/utils/formatters/block.js
function formatBlock(block) {
const transactions = (block.transactions ?? []).map((transaction) => {
if (typeof transaction === "string")
return transaction;
return formatTransaction(transaction);
});
return {
...block,
baseFeePerGas: block.baseFeePerGas ? BigInt(block.baseFeePerGas) : null,
blobGasUsed: block.blobGasUsed ? BigInt(block.blobGasUsed) : void 0,
difficulty: block.difficulty ? BigInt(block.difficulty) : void 0,
excessBlobGas: block.excessBlobGas ? BigInt(block.excessBlobGas) : void 0,
gasLimit: block.gasLimit ? BigInt(block.gasLimit) : void 0,
gasUsed: block.gasUsed ? BigInt(block.gasUsed) : void 0,
hash: block.hash ? block.hash : null,
logsBloom: block.logsBloom ? block.logsBloom : null,
nonce: block.nonce ? block.nonce : null,
number: block.number ? BigInt(block.number) : null,
size: block.size ? BigInt(block.size) : void 0,
timestamp: block.timestamp ? BigInt(block.timestamp) : void 0,
transactions,
totalDifficulty: block.totalDifficulty ? BigInt(block.totalDifficulty) : null
};
}
// node_modules/viem/_esm/actions/public/getBlock.js
async function getBlock(client, { blockHash, blockNumber, blockTag: blockTag_, includeTransactions: includeTransactions_ } = {}) {
const blockTag = blockTag_ ?? "latest";
const includeTransactions = includeTransactions_ ?? false;
const blockNumberHex = blockNumber !== void 0 ? numberToHex(blockNumber) : void 0;
let block = null;
if (blockHash) {
block = await client.request({
method: "eth_getBlockByHash",
params: [blockHash, includeTransactions]
}, { dedupe: true });
} else {
block = await client.request({
method: "eth_getBlockByNumber",
params: [blockNumberHex || blockTag, includeTransactions]
}, { dedupe: Boolean(blockNumberHex) });
}
if (!block)
throw new BlockNotFoundError({ blockHash, blockNumber });
const format = client.chain?.formatters?.block?.format || formatBlock;
return format(block);
}
// node_modules/viem/_esm/actions/public/getGasPrice.js
async function getGasPrice(client) {
const gasPrice = await client.request({
method: "eth_gasPrice"
});
return BigInt(gasPrice);
}
// node_modules/viem/_esm/actions/public/estimateMaxPriorityFeePerGas.js
async function estimateMaxPriorityFeePerGas(client, args) {
return internal_estimateMaxPriorityFeePerGas(client, args);
}
async function internal_estimateMaxPriorityFeePerGas(client, args) {
const { block: block_, chain = client.chain, request } = args || {};
try {
const maxPriorityFeePerGas = chain?.fees?.maxPriorityFeePerGas ?? chain?.fees?.defaultPriorityFee;
if (typeof maxPriorityFeePerGas === "function") {
const block = block_ || await getAction(client, getBlock, "getBlock")({});
const maxPriorityFeePerGas_ = await maxPriorityFeePerGas({
block,
client,
request
});
if (maxPriorityFeePerGas_ === null)
throw new Error();
return maxPriorityFeePerGas_;
}
if (typeof maxPriorityFeePerGas !== "undefined")
return maxPriorityFeePerGas;
const maxPriorityFeePerGasHex = await client.request({
method: "eth_maxPriorityFeePerGas"
});
return hexToBigInt(maxPriorityFeePerGasHex);
} catch {
const [block, gasPrice] = await Promise.all([
block_ ? Promise.resolve(block_) : getAction(client, getBlock, "getBlock")({}),
getAction(client, getGasPrice, "getGasPrice")({})
]);
if (typeof block.baseFeePerGas !== "bigint")
throw new Eip1559FeesNotSupportedError();
const maxPriorityFeePerGas = gasPrice - block.baseFeePerGas;
if (maxPriorityFeePerGas < 0n)
return 0n;
return maxPriorityFeePerGas;
}
}
// node_modules/viem/_esm/actions/public/estimateFeesPerGas.js
async function estimateFeesPerGas(client, args) {
return internal_estimateFeesPerGas(client, args);
}
async function internal_estimateFeesPerGas(client, args) {
const { block: block_, chain = client.chain, request, type = "eip1559" } = args || {};
const baseFeeMultiplier = await (async () => {
if (typeof chain?.fees?.baseFeeMultiplier === "function")
return chain.fees.baseFeeMultiplier({
block: block_,
client,
request
});
return chain?.fees?.baseFeeMultiplier ?? 1.2;
})();
if (baseFeeMultiplier < 1)
throw new BaseFeeScalarError();
const decimals = baseFeeMultiplier.toString().split(".")[1]?.length ?? 0;
const denominator = 10 ** decimals;
const multiply = (base) => base * BigInt(Math.ceil(baseFeeMultiplier * denominator)) / BigInt(denominator);
const block = block_ ? block_ : await getAction(client, getBlock, "getBlock")({});
if (typeof chain?.fees?.estimateFeesPerGas === "function") {
const fees = await chain.fees.estimateFeesPerGas({
block: block_,
client,
multiply,
request,
type
});
if (fees !== null)
return fees;
}
if (type === "eip1559") {
if (typeof block.baseFeePerGas !== "bigint")
throw new Eip1559FeesNotSupportedError();
const maxPriorityFeePerGas = typeof request?.maxPriorityFeePerGas === "bigint" ? request.maxPriorityFeePerGas : await internal_estimateMaxPriorityFeePerGas(client, {
block,
chain,
request
});
const baseFeePerGas = multiply(block.baseFeePerGas);
const maxFeePerGas = request?.maxFeePerGas ?? baseFeePerGas + maxPriorityFeePerGas;
return {
maxFeePerGas,
maxPriorityFeePerGas
};
}
const gasPrice = request?.gasPrice ?? multiply(await getAction(client, getGasPrice, "getGasPrice")({}));
return {
gasPrice
};
}
// node_modules/viem/_esm/actions/public/getTransactionCount.js
async function getTransactionCount(client, { address, blockTag = "latest", blockNumber }) {
const count = await client.request({
method: "eth_getTransactionCount",
params: [
address,
typeof blockNumber === "bigint" ? numberToHex(blockNumber) : blockTag
]
}, {
dedupe: Boolean(blockNumber)
});
return hexToNumber(count);
}
// node_modules/viem/_esm/utils/blob/blobsToCommitments.js
function blobsToCommitments(parameters) {
const { kzg } = parameters;
const to = parameters.to ?? (typeof parameters.blobs[0] === "string" ? "hex" : "bytes");
const blobs = typeof parameters.blobs[0] === "string" ? parameters.blobs.map((x) => hexToBytes(x)) : parameters.blobs;
const commitments = [];
for (const blob of blobs)
commitments.push(Uint8Array.from(kzg.blobToKzgCommitment(blob)));
return to === "bytes" ? commitments : commitments.map((x) => bytesToHex(x));
}
// node_modules/viem/_esm/utils/blob/blobsToProofs.js
function blobsToProofs(parameters) {
const { kzg } = parameters;
const to = parameters.to ?? (typeof parameters.blobs[0] === "string" ? "hex" : "bytes");
const blobs = typeof parameters.blobs[0] === "string" ? parameters.blobs.map((x) => hexToBytes(x)) : parameters.blobs;
const commitments = typeof parameters.commitments[0] === "string" ? parameters.commitments.map((x) => hexToBytes(x)) : parameters.commitments;
const proofs = [];
for (let i = 0; i < blobs.length; i++) {
const blob = blobs[i];
const commitment = commitments[i];
proofs.push(Uint8Array.from(kzg.computeBlobKzgProof(blob, commitment)));
}
return to === "bytes" ? proofs : proofs.map((x) => bytesToHex(x));
}
// node_modules/@noble/hashes/esm/sha256.js
var sha2562 = sha256;
// node_modules/viem/_esm/utils/hash/sha256.js
function sha2563(value, to_) {
const to = to_ || "hex";
const bytes = sha2562(isHex(value, { strict: false }) ? toBytes(value) : value);
if (to === "bytes")
return bytes;
return toHex(bytes);
}
// node_modules/viem/_esm/utils/blob/commitmentToVersionedHash.js
function commitmentToVersionedHash(parameters) {
const { commitment, version: version2 = 1 } = parameters;
const to = parameters.to ?? (typeof commitment === "string" ? "hex" : "bytes");
const versionedHash = sha2563(commitment, "bytes");
versionedHash.set([version2], 0);
return to === "bytes" ? versionedHash : bytesToHex(versionedHash);
}
// node_modules/viem/_esm/utils/blob/commitmentsToVersionedHashes.js
function commitmentsToVersionedHashes(parameters) {
const { commitments, version: version2 } = parameters;
const to = parameters.to ?? (typeof commitments[0] === "string" ? "hex" : "bytes");
const hashes = [];
for (const commitment of commitments) {
hashes.push(commitmentToVersionedHash({
commitment,
to,
version: version2
}));
}
return hashes;
}
// node_modules/viem/_esm/constants/blob.js
var blobsPerTransaction = 6;
var bytesPerFieldElement = 32;
var fieldElementsPerBlob = 4096;
var bytesPerBlob = bytesPerFieldElement * fieldElementsPerBlob;
var maxBytesPerTransaction = bytesPerBlob * blobsPerTransaction - // terminator byte (0x80).
1 - // zero byte (0x00) appended to each field element.
1 * fieldElementsPerBlob * blobsPerTransaction;
// node_modules/viem/_esm/constants/kzg.js
var versionedHashVersionKzg = 1;
// node_modules/viem/_esm/errors/blob.js
var BlobSizeTooLargeError = class extends BaseError {
constructor({ maxSize, size: size4 }) {
super("Blob size is too large.", {
metaMessages: [`Max: ${maxSize} bytes`, `Given: ${size4} bytes`],
name: "BlobSizeTooLargeError"
});
}
};
var EmptyBlobError = class extends BaseError {
constructor() {
super("Blob data must not be empty.", { name: "EmptyBlobError" });
}
};
var InvalidVersionedHashSizeError = class extends BaseError {
constructor({ hash, size: size4 }) {
super(`Versioned hash "${hash}" size is invalid.`, {
metaMessages: ["Expected: 32", `Received: ${size4}`],
name: "InvalidVersionedHashSizeError"
});
}
};
var InvalidVersionedHashVersionError = class extends BaseError {
constructor({ hash, version: version2 }) {
super(`Versioned hash "${hash}" version is invalid.`, {
metaMessages: [
`Expected: ${versionedHashVersionKzg}`,
`Received: ${version2}`
],
name: "InvalidVersionedHashVersionError"
});
}
};
// node_modules/viem/_esm/utils/blob/toBlobs.js
function toBlobs(parameters) {
const to = parameters.to ?? (typeof parameters.data === "string" ? "hex" : "bytes");
const data = typeof parameters.data === "string" ? hexToBytes(parameters.data) : parameters.data;
const size_ = size(data);
if (!size_)
throw new EmptyBlobError();
if (size_ > maxBytesPerTransaction)
throw new BlobSizeTooLargeError({
maxSize: maxBytesPerTransaction,
size: size_
});
const blobs = [];
let active = true;
let position = 0;
while (active) {
const blob = createCursor(new Uint8Array(bytesPerBlob));
let size4 = 0;
while (size4 < fieldElementsPerBlob) {
const bytes = data.slice(position, position + (bytesPerFieldElement - 1));
blob.pushByte(0);
blob.pushBytes(bytes);
if (bytes.length < 31) {
blob.pushByte(128);
active = false;
break;
}
size4++;
position += 31;
}
blobs.push(blob);
}
return to === "bytes" ? blobs.map((x) => x.bytes) : blobs.map((x) => bytesToHex(x.bytes));
}
// node_modules/viem/_esm/utils/blob/toBlobSidecars.js
function toBlobSidecars(parameters) {
const { data, kzg, to } = parameters;
const blobs = parameters.blobs ?? toBlobs({ data, to });
const commitments = parameters.commitments ?? blobsToCommitments({ blobs, kzg, to });
const proofs = parameters.proofs ?? blobsToProofs({ blobs, commitments, kzg, to });
const sidecars = [];
for (let i = 0; i < blobs.length; i++)
sidecars.push({
blob: blobs[i],
commitment: commitments[i],
proof: proofs[i]
});
return sidecars;
}
// node_modules/viem/_esm/utils/transaction/getTransactionType.js
function getTransactionType(transaction) {
if (transaction.type)
return transaction.type;
if (typeof transaction.authorizationList !== "undefined")
return "eip7702";
if (typeof transaction.blobs !== "undefined" || typeof transaction.blobVersionedHashes !== "undefined" || typeof transaction.maxFeePerBlobGas !== "undefined" || typeof transaction.sidecars !== "undefined")
return "eip4844";
if (typeof transaction.maxFeePerGas !== "undefined" || typeof transaction.maxPriorityFeePerGas !== "undefined") {
return "eip1559";
}
if (typeof transaction.gasPrice !== "undefined") {
if (typeof transaction.accessList !== "undefined")
return "eip2930";
return "legacy";
}
throw new InvalidSerializableTransactionError({ transaction });
}
// node_modules/viem/_esm/actions/public/getChainId.js
async function getChainId(client) {
const chainIdHex = await client.request({
method: "eth_chainId"
}, { dedupe: true });
return hexToNumber(chainIdHex);
}
// node_modules/viem/_esm/actions/wallet/prepareTransactionRequest.js
var defaultParameters = [
"blobVersionedHashes",
"chainId",
"fees",
"gas",
"nonce",
"type"
];
var eip1559NetworkCache = /* @__PURE__ */ new Map();
async function prepareTransactionRequest(client, args) {
const { account: account_ = client.account, blobs, chain, gas, kzg, nonce, nonceManager, parameters = defaultParameters, type } = args;
const account = account_ ? parseAccount(account_) : account_;
const request = { ...args, ...account ? { from: account?.address } : {} };
let block;
async function getBlock2() {
if (block)
return block;
block = await getAction(client, getBlock, "getBlock")({ blockTag: "latest" });
return block;
}
let chainId;
async function getChainId2() {
if (chainId)
return chainId;
if (chain)
return chain.id;
if (typeof args.chainId !== "undefined")
return args.chainId;
const chainId_ = await getAction(client, getChainId, "getChainId")({});
chainId = chainId_;
return chainId;
}
if (parameters.includes("nonce") && typeof nonce === "undefined" && account) {
if (nonceManager) {
const chainId2 = await getChainId2();
request.nonce = await nonceManager.consume({
address: account.address,
chainId: chainId2,
client
});
} else {
request.nonce = await getAction(client, getTransactionCount, "getTransactionCount")({
address: account.address,
blockTag: "pending"
});
}
}
if ((parameters.includes("blobVersionedHashes") || parameters.includes("sidecars")) && blobs && kzg) {
const commitments = blobsToCommitments({ blobs, kzg });
if (parameters.includes("blobVersionedHashes")) {
const versionedHashes = commitmentsToVersionedHashes({
commitments,
to: "hex"
});
request.blobVersionedHashes = versionedHashes;
}
if (parameters.includes("sidecars")) {
const proofs = blobsToProofs({ blobs, commitments, kzg });
const sidecars = toBlobSidecars({
blobs,
commitments,
proofs,
to: "hex"
});
request.sidecars = sidecars;
}
}
if (parameters.includes("chainId"))
request.chainId = await getChainId2();
if ((parameters.includes("fees") || parameters.includes("type")) && typeof type === "undefined") {
try {
request.type = getTransactionType(request);
} catch {
let isEip1559Network = eip1559NetworkCache.get(client.uid);
if (typeof isEip1559Network === "undefined") {
const block2 = await getBlock2();
isEip1559Network = typeof block2?.baseFeePerGas === "bigint";
eip1559NetworkCache.set(client.uid, isEip1559Network);
}
request.type = isEip1559Network ? "eip1559" : "legacy";
}
}
if (parameters.includes("fees")) {
if (request.type !== "legacy" && request.type !== "eip2930") {
if (typeof request.maxFeePerGas === "undefined" || typeof request.maxPriorityFeePerGas === "undefined") {
const block2 = await getBlock2();
const { maxFeePerGas, maxPriorityFeePerGas } = await internal_estimateFeesPerGas(client, {
block: block2,
chain,
request
});
if (typeof args.maxPriorityFeePerGas === "undefined" && args.maxFeePerGas && args.maxFeePerGas < maxPriorityFeePerGas)
throw new MaxFeePerGasTooLowError({
maxPriorityFeePerGas
});
request.maxPriorityFeePerGas = maxPriorityFeePerGas;
request.maxFeePerGas = maxFeePerGas;
}
} else {
if (typeof args.maxFeePerGas !== "undefined" || typeof args.maxPriorityFeePerGas !== "undefined")
throw new Eip1559FeesNotSupportedError();
if (typeof args.gasPrice === "undefined") {
const block2 = await getBlock2();
const { gasPrice: gasPrice_ } = await internal_estimateFeesPerGas(client, {
block: block2,
chain,
request,
type: "legacy"
});
request.gasPrice = gasPrice_;
}
}
}
if (parameters.includes("gas") && typeof gas === "undefined")
request.gas = await getAction(client, estimateGas, "estimateGas")({
...request,
account: account ? { address: account.address, type: "json-rpc" } : account
});
assertRequest(request);
delete request.parameters;
return request;
}
// node_modules/viem/_esm/actions/public/getBalance.js
async function getBalance(client, { address, blockNumber, blockTag = "latest" }) {
const blockNumberHex = typeof blockNumber === "bigint" ? numberToHex(blockNumber) : void 0;
const balance = await client.request({
method: "eth_getBalance",
params: [address, blockNumberHex || blockTag]
});
return BigInt(balance);
}
// node_modules/viem/_esm/actions/public/estimateGas.js
async function estimateGas(client, args) {
const { account: account_ = client.account } = args;
const account = account_ ? parseAccount(account_) : void 0;
try {
let estimateGas_rpc2 = function(parameters) {
const { block: block2, request: request2, rpcStateOverride: rpcStateOverride2 } = parameters;
return client.request({
method: "eth_estimateGas",
params: rpcStateOverride2 ? [request2, block2 ?? "latest", rpcStateOverride2] : block2 ? [request2, block2] : [request2]
});
};
var estimateGas_rpc = estimateGas_rpc2;
const { accessList, authorizationList, blobs, blobVersionedHashes, blockNumber, blockTag, data, gas, gasPrice, maxFeePerBlobGas, maxFeePerGas, maxPriorityFeePerGas, nonce, value, stateOverride, ...rest } = await prepareTransactionRequest(client, {
...args,
parameters: (
// Some RPC Providers do not compute versioned hashes from blobs. We will need
// to compute them.
account?.type === "local" ? void 0 : ["blobVersionedHashes"]
)
});
const blockNumberHex = typeof blockNumber === "bigint" ? numberToHex(blockNumber) : void 0;
const block = blockNumberHex || blockTag;
const rpcStateOverride = serializeStateOverride(stateOverride);
const to = await (async () => {
if (rest.to)
return rest.to;
if (authorizationList && authorizationList.length > 0)
return await recoverAuthorizationAddress({
authorization: authorizationList[0]
}).catch(() => {
throw new BaseError("`to` is required. Could not infer from `authorizationList`");
});
return void 0;
})();
assertRequest(args);
const chainFormat = client.chain?.formatters?.transactionRequest?.format;
const format = chainFormat || formatTransactionRequest;
const request = format({
// Pick out extra data that might exist on the chain's transaction request type.
...extract(rest, { format: chainFormat }),
from: account?.address,
accessList,
authorizationList,
blobs,
blobVersionedHashes,
data,
gas,
gasPrice,
maxFeePerBlobGas,
maxFeePerGas,
maxPriorityFeePerGas,
nonce,
to,
value
});
let estimate = BigInt(await estimateGas_rpc2({ block, request, rpcStateOverride }));
if (authorizationList) {
const value2 = await getBalance(client, { address: request.from });
const estimates = await Promise.all(authorizationList.map(async (authorization) => {
const { address } = authorization;
const estimate2 = await estimateGas_rpc2({
block,
request: {
authorizationList: void 0,
data,
from: account?.address,
to: address,
value: numberToHex(value2)
},
rpcStateOverride
}).catch(() => 100000n);
return 2n * BigInt(estimate2);
}));
estimate += estimates.reduce((acc, curr) => acc + curr, 0n);
}
return estimate;
} catch (err) {
throw getEstimateGasError(err, {
...args,
account,
chain: client.chain
});
}
}
// node_modules/viem/_esm/actions/public/estimateContractGas.js
async function estimateContractGas(client, parameters) {
const { abi: abi2, address, args, functionName, dataSuffix, ...request } = parameters;
const data = encodeFunctionData({
abi: abi2,
args,
functionName
});
try {
const gas = await getAction(client, estimateGas, "estimateGas")({
data: `${data}${dataSuffix ? dataSuffix.replace("0x", "") : ""}`,
to: address,
...request
});
return gas;
} catch (error) {
const account = request.account ? parseAccount(request.account) : void 0;
throw getContractError(error, {
abi: abi2,
address,
args,
docsPath: "/docs/contract/estimateContractGas",
functionName,
sender: account?.address
});
}
}
// node_modules/viem/_esm/utils/abi/decodeEventLog.js
var docsPath2 = "/docs/contract/decodeEventLog";
function decodeEventLog(parameters) {
const { abi: abi2, data, strict: strict_, topics } = parameters;
const strict = strict_ ?? true;
const [signature, ...argTopics] = topics;
if (!signature)
throw new AbiEventSignatureEmptyTopicsError({ docsPath: docsPath2 });
const abiItem = abi2.find((x) => x.type === "event" && signature === toEventSelector(formatAbiItem(x)));
if (!(abiItem && "name" in abiItem) || abiItem.type !== "event")
throw new AbiEventSignatureNotFoundError(signature, { docsPath: docsPath2 });
const { name, inputs } = abiItem;
const isUnnamed = inputs?.some((x) => !("name" in x && x.name));
const args = isUnnamed ? [] : {};
const indexedInputs = inputs.map((x, i) => [x, i]).filter(([x]) => "indexed" in x && x.indexed);
for (let i = 0; i < indexedInputs.length; i++) {
const [param, argIndex] = indexedInputs[i];
const topic = argTopics[i];
if (!topic)
throw new DecodeLogTopicsMismatch({
abiItem,
param
});
args[isUnnamed ? argIndex : param.name || argIndex] = decodeTopic({
param,
value: topic
});
}
const nonIndexedInputs = inputs.filter((x) => !("indexed" in x && x.indexed));
if (nonIndexedInputs.length > 0) {
if (data && data !== "0x") {
try {
const decodedData = decodeAbiParameters(nonIndexedInputs, data);
if (decodedData) {
if (isUnnamed)
for (let i = 0; i < inputs.length; i++)
args[i] = args[i] ?? decodedData.shift();
else
for (let i = 0; i < nonIndexedInputs.length; i++)
args[nonIndexedInputs[i].name] = decodedData[i];
}
} catch (err) {
if (strict) {
if (err instanceof AbiDecodingDataSizeTooSmallError || err instanceof PositionOutOfBoundsError)
throw new DecodeLogDataMismatch({
abiItem,
data,
params: nonIndexedInputs,
size: size(data)
});
throw err;
}
}
} else if (strict) {
throw new DecodeLogDataMismatch({
abiItem,
data: "0x",
params: nonIndexedInputs,
size: 0
});
}
}
return {
eventName: name,
args: Object.values(args).length > 0 ? args : void 0
};
}
function decodeTopic({ param, value }) {
if (param.type === "string" || param.type === "bytes" || param.type === "tuple" || param.type.match(/^(.*)\[(\d+)?\]$/))
return value;
const decodedArg = decodeAbiParameters([param], value) || [];
return decodedArg[0];
}
// node_modules/viem/_esm/utils/abi/parseEventLogs.js
function parseEventLogs(parameters) {
const { abi: abi2, args, logs, strict = true } = parameters;
const eventName = (() => {
if (!parameters.eventName)
return void 0;
if (Array.isArray(parameters.eventName))
return parameters.eventName;
return [parameters.eventName];
})();
return logs.map((log) => {
try {
const abiItem = abi2.find((abiItem2) => abiItem2.type === "event" && log.topics[0] === toEventSelector(abiItem2));
if (!abiItem)
return null;
const event = decodeEventLog({
...log,
abi: [abiItem],
strict
});
if (eventName && !eventName.includes(event.eventName))
return null;
if (!includesArgs({
args: event.args,
inputs: abiItem.inputs,
matchArgs: args
}))
return null;
return { ...event, ...log };
} catch (err) {
let eventName2;
let isUnnamed;
if (err instanceof AbiEventSignatureNotFoundError)
return null;
if (err instanceof DecodeLogDataMismatch || err instanceof DecodeLogTopicsMismatch) {
if (strict)
return null;
eventName2 = err.abiItem.name;
isUnnamed = err.abiItem.inputs?.some((x) => !("name" in x && x.name));
}
return { ...log, args: isUnnamed ? [] : {}, eventName: eventName2 };
}
}).filter(Boolean);
}
function includesArgs(parameters) {
const { args, inputs, matchArgs } = parameters;
if (!matchArgs)
return true;
if (!args)
return false;
function isEqual(input, value, arg) {
try {
if (input.type === "address")
return isAddressEqual(value, arg);
if (input.type === "string" || input.type === "bytes")
return keccak256(toBytes(value)) === arg;
return value === arg;
} catch {
return false;
}
}
if (Array.isArray(args) && Array.isArray(matchArgs)) {
return matchArgs.every((value, index2) => {
if (value === null || value === void 0)
return true;
const input = inputs[index2];
if (!input)
return false;
const value_ = Array.isArray(value) ? value : [value];
return value_.some((value2) => isEqual(input, value2, args[index2]));
});
}
if (typeof args === "object" && !Array.isArray(args) && typeof matchArgs === "object" && !Array.isArray(matchArgs))
return Object.entries(matchArgs).every(([key, value]) => {
if (value === null || value === void 0)
return true;
const input = inputs.find((input2) => input2.name === key);
if (!input)
return false;
const value_ = Array.isArray(value) ? value : [value];
return value_.some((value2) => isEqual(input, value2, args[key]));
});
return false;
}
// node_modules/viem/_esm/utils/formatters/log.js
function formatLog(log, { args, eventName } = {}) {
return {
...log,
blockHash: log.blockHash ? log.blockHash : null,
blockNumber: log.blockNumber ? BigInt(log.blockNumber) : null,
logIndex: log.logIndex ? Number(log.logIndex) : null,
transactionHash: log.transactionHash ? log.transactionHash : null,
transactionIndex: log.transactionIndex ? Number(log.transactionIndex) : null,
...eventName ? { args, eventName } : {}
};
}
// node_modules/viem/_esm/actions/public/getLogs.js
async function getLogs(client, { address, blockHash, fromBlock, toBlock, event, events: events_, args, strict: strict_ } = {}) {
const strict = strict_ ?? false;
const events = events_ ?? (event ? [event] : void 0);
let topics = [];
if (events) {
const encoded = events.flatMap((event2) => encodeEventTopics({
abi: [event2],
eventName: event2.name,
args: events_ ? void 0 : args
}));
topics = [encoded];
if (event)
topics = topics[0];
}
let logs;
if (blockHash) {
logs = await client.request({
method: "eth_getLogs",
params: [{ address, topics, blockHash }]
});
} else {
logs = await client.request({
method: "eth_getLogs",
params: [
{
address,
topics,
fromBlock: typeof fromBlock === "bigint" ? numberToHex(fromBlock) : fromBlock,
toBlock: typeof toBlock === "bigint" ? numberToHex(toBlock) : toBlock
}
]
});
}
const formattedLogs = logs.map((log) => formatLog(log));
if (!events)
return formattedLogs;
return parseEventLogs({
abi: events,
args,
logs: formattedLogs,
strict
});
}
// node_modules/viem/_esm/actions/public/getContractEvents.js
async function getContractEvents(client, parameters) {
const { abi: abi2, address, args, blockHash, eventName, fromBlock, toBlock, strict } = parameters;
const event = eventName ? getAbiItem({ abi: abi2, name: eventName }) : void 0;
const events = !event ? abi2.filter((x) => x.type === "event") : void 0;
return getAction(client, getLogs, "getLogs")({
address,
args,
blockHash,
event,
events,
fromBlock,
toBlock,
strict
});
}
// node_modules/viem/_esm/actions/public/readContract.js
async function readContract(client, parameters) {
const { abi: abi2, address, args, functionName, ...rest } = parameters;
const calldata = encodeFunctionData({
abi: abi2,
args,
functionName
});
try {
const { data } = await getAction(client, call, "call")({
...rest,
data: calldata,
to: address
});
return decodeFunctionResult({
abi: abi2,
args,
functionName,
data: data || "0x"
});
} catch (error) {
throw getContractError(error, {
abi: abi2,
address,
args,
docsPath: "/docs/contract/readContract",
functionName
});
}
}
// node_modules/viem/_esm/actions/public/simulateContract.js
async function simulateContract(client, parameters) {
const { abi: abi2, address, args, dataSuffix, functionName, ...callRequest } = parameters;
const account = callRequest.account ? parseAccount(callRequest.account) : client.account;
const calldata = encodeFunctionData({ abi: abi2, args, functionName });
try {
const { data } = await getAction(client, call, "call")({
batch: false,
data: `${calldata}${dataSuffix ? dataSuffix.replace("0x", "") : ""}`,
to: address,
...callRequest,
account
});
const result = decodeFunctionResult({
abi: abi2,
args,
functionName,
data: data || "0x"
});
const minimizedAbi = abi2.filter((abiItem) => "name" in abiItem && abiItem.name === parameters.functionName);
return {
result,
request: {
abi: minimizedAbi,
address,
args,
dataSuffix,
functionName,
...callRequest,
account
}
};
} catch (error) {
throw getContractError(error, {
abi: abi2,
address,
args,
docsPath: "/docs/c