UNPKG

@pod-protocol/sdk

Version:

TypeScript SDK for PoD Protocol - AI agent communication on Solana

1,048 lines (1,024 loc) 40.3 kB
// src/codes.ts var SOLANA_ERROR__MALFORMED_JSON_RPC_ERROR = 10; var SOLANA_ERROR__JSON_RPC__PARSE_ERROR = -32700; var SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR = -32603; var SOLANA_ERROR__JSON_RPC__INVALID_PARAMS = -32602; var SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND = -32601; var SOLANA_ERROR__JSON_RPC__INVALID_REQUEST = -32600; var SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION = -32015; var SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET = -32014; var SOLANA_ERROR__JSON_RPC__SCAN_ERROR = -32012; var SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX = -32010; var SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED = -32009; var SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED = -32007; var SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE = -32006; var SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE = -32004; var SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE = -32002; var SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP = -32001; var SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH = 28e5; var SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE = 2800001; var SOLANA_ERROR__ADDRESSES__INVALID_ED25519_PUBLIC_KEY = 2800003; var SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED = 2800006; var SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED = 2800007; var SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE = 2800008; var SOLANA_ERROR__ADDRESSES__FAILED_TO_FIND_VIABLE_PDA_BUMP_SEED = 2800009; var SOLANA_ERROR__ACCOUNTS__ACCOUNT_NOT_FOUND = 323e4; var SOLANA_ERROR__ACCOUNTS__ONE_OR_MORE_ACCOUNTS_NOT_FOUND = 32300001; var SOLANA_ERROR__ACCOUNTS__FAILED_TO_DECODE_ACCOUNT = 3230002; var SOLANA_ERROR__SUBTLE_CRYPTO__DIGEST_UNIMPLEMENTED = 3610001; var SOLANA_ERROR__SUBTLE_CRYPTO__ED25519_ALGORITHM_UNIMPLEMENTED = 3610002; var SOLANA_ERROR__SUBTLE_CRYPTO__EXPORT_FUNCTION_UNIMPLEMENTED = 3610003; var SOLANA_ERROR__SUBTLE_CRYPTO__GENERATE_FUNCTION_UNIMPLEMENTED = 3610004; var SOLANA_ERROR__SUBTLE_CRYPTO__SIGN_FUNCTION_UNIMPLEMENTED = 3610005; var SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN = 4615e3; var SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM = 4615026; var SOLANA_ERROR__INSTRUCTION_ERROR__BORSH_IO_ERROR = 4615045; var SOLANA_ERROR__TRANSACTION__ADDRESSES_CANNOT_SIGN_TRANSACTION = 5663015; var SOLANA_ERROR__TRANSACTION_ERROR__UNKNOWN = 705e4; var SOLANA_ERROR__TRANSACTION_ERROR__DUPLICATE_INSTRUCTION = 7050030; var SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_RENT = 7050031; var SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_EXECUTION_TEMPORARILY_RESTRICTED = 7050035; var SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY = 8078e3; var SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH = 8078001; var SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH = 8078002; var SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH = 8078004; var SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH = 8078005; var SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH = 8078006; var SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS = 8078007; var SOLANA_ERROR__CODECS__ENUM_DISCRIMINATOR_OUT_OF_RANGE = 8078008; var SOLANA_ERROR__CODECS__INVALID_DISCRIMINATED_UNION_VARIANT = 8078009; var SOLANA_ERROR__CODECS__INVALID_ENUM_VARIANT = 8078010; var SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE = 8078011; var SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE = 8078012; var SOLANA_ERROR__CODECS__UNION_VARIANT_OUT_OF_RANGE = 8078017; var SOLANA_ERROR__CODECS__INVALID_CONSTANT = 8078018; var SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS = 8078022; var SOLANA_ERROR__RPC__INTEGER_OVERFLOW = 81e5; var SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR = 8100002; var SOLANA_ERROR__RPC__API_PLAN_MISSING_FOR_RPC_METHOD = 8100003; var SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN = 819e4; var SOLANA_ERROR__RPC_SUBSCRIPTIONS__EXPECTED_SERVER_SUBSCRIPTION_ID = 8190001; var SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CLOSED_BEFORE_MESSAGE_BUFFERED = 8190002; var SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED = 8190003; var SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT = 8190004; var SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING = 99e5; var SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE = 9900001; var SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED = 9900004; // src/context.ts function encodeValue(value) { if (Array.isArray(value)) { const commaSeparatedValues = value.map(encodeValue).join( "%2C%20" /* ", " */ ); return "%5B" + commaSeparatedValues + /* "]" */ "%5D"; } else if (typeof value === "bigint") { return `${value}n`; } else { return encodeURIComponent( String( value != null && Object.getPrototypeOf(value) === null ? ( // Plain objects with no prototype don't have a `toString` method. // Convert them before stringifying them. { ...value } ) : value ) ); } } function encodeObjectContextEntry([key, value]) { return `${key}=${encodeValue(value)}`; } function encodeContextObject(context) { const searchParamsString = Object.entries(context).map(encodeObjectContextEntry).join("&"); return Buffer.from(searchParamsString, "utf8").toString("base64") ; } function getErrorMessage(code, context = {}) { { let decodingAdviceMessage = `Solana error #${code}; Decode this error by running \`npx @solana/errors decode -- ${code}`; if (Object.keys(context).length) { decodingAdviceMessage += ` '${encodeContextObject(context)}'`; } return `${decodingAdviceMessage}\``; } } // src/error.ts function isSolanaError(e, code) { const isSolanaError2 = e instanceof Error && e.name === "SolanaError"; if (isSolanaError2) { if (code !== void 0) { return e.context.__code === code; } return true; } return false; } var SolanaError = class extends Error { /** * Indicates the root cause of this {@link SolanaError}, if any. * * For example, a transaction error might have an instruction error as its root cause. In this * case, you will be able to access the instruction error on the transaction error as `cause`. */ cause = this.cause; /** * Contains context that can assist in understanding or recovering from a {@link SolanaError}. */ context; constructor(...[code, contextAndErrorOptions]) { let context; let errorOptions; if (contextAndErrorOptions) { const { cause, ...contextRest } = contextAndErrorOptions; if (cause) { errorOptions = { cause }; } if (Object.keys(contextRest).length > 0) { context = contextRest; } } const message = getErrorMessage(code, context); super(message, errorOptions); this.context = { __code: code, ...context }; this.name = "SolanaError"; } }; // src/stack-trace.ts function safeCaptureStackTrace(...args) { if ("captureStackTrace" in Error && typeof Error.captureStackTrace === "function") { Error.captureStackTrace(...args); } } // src/rpc-enum-errors.ts function getSolanaErrorFromRpcError({ errorCodeBaseOffset, getErrorContext, orderedErrorNames, rpcEnumError }, constructorOpt) { let rpcErrorName; let rpcErrorContext; if (typeof rpcEnumError === "string") { rpcErrorName = rpcEnumError; } else { rpcErrorName = Object.keys(rpcEnumError)[0]; rpcErrorContext = rpcEnumError[rpcErrorName]; } const codeOffset = orderedErrorNames.indexOf(rpcErrorName); const errorCode = errorCodeBaseOffset + codeOffset; const errorContext = getErrorContext(errorCode, rpcErrorName, rpcErrorContext); const err = new SolanaError(errorCode, errorContext); safeCaptureStackTrace(err, constructorOpt); return err; } // src/instruction-error.ts var ORDERED_ERROR_NAMES = [ // Keep synced with RPC source: https://github.com/anza-xyz/agave/blob/master/sdk/program/src/instruction.rs // If this list ever gets too large, consider implementing a compression strategy like this: // https://gist.github.com/steveluscher/aaa7cbbb5433b1197983908a40860c47 "GenericError", "InvalidArgument", "InvalidInstructionData", "InvalidAccountData", "AccountDataTooSmall", "InsufficientFunds", "IncorrectProgramId", "MissingRequiredSignature", "AccountAlreadyInitialized", "UninitializedAccount", "UnbalancedInstruction", "ModifiedProgramId", "ExternalAccountLamportSpend", "ExternalAccountDataModified", "ReadonlyLamportChange", "ReadonlyDataModified", "DuplicateAccountIndex", "ExecutableModified", "RentEpochModified", "NotEnoughAccountKeys", "AccountDataSizeChanged", "AccountNotExecutable", "AccountBorrowFailed", "AccountBorrowOutstanding", "DuplicateAccountOutOfSync", "Custom", "InvalidError", "ExecutableDataModified", "ExecutableLamportChange", "ExecutableAccountNotRentExempt", "UnsupportedProgramId", "CallDepth", "MissingAccount", "ReentrancyNotAllowed", "MaxSeedLengthExceeded", "InvalidSeeds", "InvalidRealloc", "ComputationalBudgetExceeded", "PrivilegeEscalation", "ProgramEnvironmentSetupFailure", "ProgramFailedToComplete", "ProgramFailedToCompile", "Immutable", "IncorrectAuthority", "BorshIoError", "AccountNotRentExempt", "InvalidAccountOwner", "ArithmeticOverflow", "UnsupportedSysvar", "IllegalOwner", "MaxAccountsDataAllocationsExceeded", "MaxAccountsExceeded", "MaxInstructionTraceLengthExceeded", "BuiltinProgramsMustConsumeComputeUnits" ]; function getSolanaErrorFromInstructionError(index, instructionError) { const numberIndex = Number(index); return getSolanaErrorFromRpcError( { errorCodeBaseOffset: 4615001, getErrorContext(errorCode, rpcErrorName, rpcErrorContext) { if (errorCode === SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN) { return { errorName: rpcErrorName, index: numberIndex, ...rpcErrorContext !== void 0 ? { instructionErrorContext: rpcErrorContext } : null }; } else if (errorCode === SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM) { return { code: Number(rpcErrorContext), index: numberIndex }; } else if (errorCode === SOLANA_ERROR__INSTRUCTION_ERROR__BORSH_IO_ERROR) { return { encodedData: rpcErrorContext, index: numberIndex }; } return { index: numberIndex }; }, orderedErrorNames: ORDERED_ERROR_NAMES, rpcEnumError: instructionError }, getSolanaErrorFromInstructionError ); } // src/transaction-error.ts var ORDERED_ERROR_NAMES2 = [ // Keep synced with RPC source: https://github.com/anza-xyz/agave/blob/master/sdk/src/transaction/error.rs // If this list ever gets too large, consider implementing a compression strategy like this: // https://gist.github.com/steveluscher/aaa7cbbb5433b1197983908a40860c47 "AccountInUse", "AccountLoadedTwice", "AccountNotFound", "ProgramAccountNotFound", "InsufficientFundsForFee", "InvalidAccountForFee", "AlreadyProcessed", "BlockhashNotFound", // `InstructionError` intentionally omitted; delegated to `getSolanaErrorFromInstructionError` "CallChainTooDeep", "MissingSignatureForFee", "InvalidAccountIndex", "SignatureFailure", "InvalidProgramForExecution", "SanitizeFailure", "ClusterMaintenance", "AccountBorrowOutstanding", "WouldExceedMaxBlockCostLimit", "UnsupportedVersion", "InvalidWritableAccount", "WouldExceedMaxAccountCostLimit", "WouldExceedAccountDataBlockLimit", "TooManyAccountLocks", "AddressLookupTableNotFound", "InvalidAddressLookupTableOwner", "InvalidAddressLookupTableData", "InvalidAddressLookupTableIndex", "InvalidRentPayingAccount", "WouldExceedMaxVoteCostLimit", "WouldExceedAccountDataTotalLimit", "DuplicateInstruction", "InsufficientFundsForRent", "MaxLoadedAccountsDataSizeExceeded", "InvalidLoadedAccountsDataSizeLimit", "ResanitizationNeeded", "ProgramExecutionTemporarilyRestricted", "UnbalancedTransaction" ]; function getSolanaErrorFromTransactionError(transactionError) { if (typeof transactionError === "object" && "InstructionError" in transactionError) { return getSolanaErrorFromInstructionError( ...transactionError.InstructionError ); } return getSolanaErrorFromRpcError( { errorCodeBaseOffset: 7050001, getErrorContext(errorCode, rpcErrorName, rpcErrorContext) { if (errorCode === SOLANA_ERROR__TRANSACTION_ERROR__UNKNOWN) { return { errorName: rpcErrorName, ...rpcErrorContext !== void 0 ? { transactionErrorContext: rpcErrorContext } : null }; } else if (errorCode === SOLANA_ERROR__TRANSACTION_ERROR__DUPLICATE_INSTRUCTION) { return { index: Number(rpcErrorContext) }; } else if (errorCode === SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_RENT || errorCode === SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_EXECUTION_TEMPORARILY_RESTRICTED) { return { accountIndex: Number(rpcErrorContext.account_index) }; } }, orderedErrorNames: ORDERED_ERROR_NAMES2, rpcEnumError: transactionError }, getSolanaErrorFromTransactionError ); } // src/json-rpc-error.ts function getSolanaErrorFromJsonRpcError(putativeErrorResponse) { let out; if (isRpcErrorResponse(putativeErrorResponse)) { const { code: rawCode, data, message } = putativeErrorResponse; const code = Number(rawCode); if (code === SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE) { const { err, ...preflightErrorContext } = data; const causeObject = err ? { cause: getSolanaErrorFromTransactionError(err) } : null; out = new SolanaError(SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE, { ...preflightErrorContext, ...causeObject }); } else { let errorContext; switch (code) { case SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR: case SOLANA_ERROR__JSON_RPC__INVALID_PARAMS: case SOLANA_ERROR__JSON_RPC__INVALID_REQUEST: case SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND: case SOLANA_ERROR__JSON_RPC__PARSE_ERROR: case SOLANA_ERROR__JSON_RPC__SCAN_ERROR: case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP: case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE: case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET: case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX: case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED: case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED: case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE: case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION: errorContext = { __serverMessage: message }; break; default: if (typeof data === "object" && !Array.isArray(data)) { errorContext = data; } } out = new SolanaError(code, errorContext); } } else { const message = typeof putativeErrorResponse === "object" && putativeErrorResponse !== null && "message" in putativeErrorResponse && typeof putativeErrorResponse.message === "string" ? putativeErrorResponse.message : "Malformed JSON-RPC error with no message attribute"; out = new SolanaError(SOLANA_ERROR__MALFORMED_JSON_RPC_ERROR, { error: putativeErrorResponse, message }); } safeCaptureStackTrace(out, getSolanaErrorFromJsonRpcError); return out; } function isRpcErrorResponse(value) { return typeof value === "object" && value !== null && "code" in value && "message" in value && (typeof value.code === "number" || typeof value.code === "bigint") && typeof value.message === "string"; } var padBytes = (bytes, length) => { if (bytes.length >= length) return bytes; const paddedBytes = new Uint8Array(length).fill(0); paddedBytes.set(bytes); return paddedBytes; }; var fixBytes = (bytes, length) => padBytes(bytes.length <= length ? bytes : bytes.slice(0, length), length); function containsBytes(data, bytes, offset) { const slice = offset === 0 && data.length === bytes.length ? data : data.slice(offset, offset + bytes.length); if (slice.length !== bytes.length) return false; return bytes.every((b, i) => b === slice[i]); } function getEncodedSize(value, encoder) { return "fixedSize" in encoder ? encoder.fixedSize : encoder.getSizeFromValue(value); } function createEncoder(encoder) { return Object.freeze({ ...encoder, encode: (value) => { const bytes = new Uint8Array(getEncodedSize(value, encoder)); encoder.write(value, bytes, 0); return bytes; } }); } function createDecoder(decoder) { return Object.freeze({ ...decoder, decode: (bytes, offset = 0) => decoder.read(bytes, offset)[0] }); } function isFixedSize(codec) { return "fixedSize" in codec && typeof codec.fixedSize === "number"; } function assertIsFixedSize(codec) { if (!isFixedSize(codec)) { throw new SolanaError(SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH); } } function isVariableSize(codec) { return !isFixedSize(codec); } function combineCodec(encoder, decoder) { if (isFixedSize(encoder) !== isFixedSize(decoder)) { throw new SolanaError(SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH); } if (isFixedSize(encoder) && isFixedSize(decoder) && encoder.fixedSize !== decoder.fixedSize) { throw new SolanaError(SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH, { decoderFixedSize: decoder.fixedSize, encoderFixedSize: encoder.fixedSize }); } if (!isFixedSize(encoder) && !isFixedSize(decoder) && encoder.maxSize !== decoder.maxSize) { throw new SolanaError(SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH, { decoderMaxSize: decoder.maxSize, encoderMaxSize: encoder.maxSize }); } return { ...decoder, ...encoder, decode: decoder.decode, encode: encoder.encode, read: decoder.read, write: encoder.write }; } function assertByteArrayIsNotEmptyForCodec(codecDescription, bytes, offset = 0) { if (bytes.length - offset <= 0) { throw new SolanaError(SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY, { codecDescription }); } } function assertByteArrayHasEnoughBytesForCodec(codecDescription, expected, bytes, offset = 0) { const bytesLength = bytes.length - offset; if (bytesLength < expected) { throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH, { bytesLength, codecDescription, expected }); } } // src/add-codec-size-prefix.ts function addEncoderSizePrefix(encoder, prefix) { const write = (value, bytes, offset) => { const encoderBytes = encoder.encode(value); offset = prefix.write(encoderBytes.length, bytes, offset); bytes.set(encoderBytes, offset); return offset + encoderBytes.length; }; if (isFixedSize(prefix) && isFixedSize(encoder)) { return createEncoder({ ...encoder, fixedSize: prefix.fixedSize + encoder.fixedSize, write }); } const prefixMaxSize = isFixedSize(prefix) ? prefix.fixedSize : prefix.maxSize ?? null; const encoderMaxSize = isFixedSize(encoder) ? encoder.fixedSize : encoder.maxSize ?? null; const maxSize = prefixMaxSize !== null && encoderMaxSize !== null ? prefixMaxSize + encoderMaxSize : null; return createEncoder({ ...encoder, ...maxSize !== null ? { maxSize } : {}, getSizeFromValue: (value) => { const encoderSize = getEncodedSize(value, encoder); return getEncodedSize(encoderSize, prefix) + encoderSize; }, write }); } function addDecoderSizePrefix(decoder, prefix) { const read = (bytes, offset) => { const [bigintSize, decoderOffset] = prefix.read(bytes, offset); const size = Number(bigintSize); offset = decoderOffset; if (offset > 0 || bytes.length > size) { bytes = bytes.slice(offset, offset + size); } assertByteArrayHasEnoughBytesForCodec("addDecoderSizePrefix", size, bytes); return [decoder.decode(bytes), offset + size]; }; if (isFixedSize(prefix) && isFixedSize(decoder)) { return createDecoder({ ...decoder, fixedSize: prefix.fixedSize + decoder.fixedSize, read }); } const prefixMaxSize = isFixedSize(prefix) ? prefix.fixedSize : prefix.maxSize ?? null; const decoderMaxSize = isFixedSize(decoder) ? decoder.fixedSize : decoder.maxSize ?? null; const maxSize = prefixMaxSize !== null && decoderMaxSize !== null ? prefixMaxSize + decoderMaxSize : null; return createDecoder({ ...decoder, ...maxSize !== null ? { maxSize } : {}, read }); } // src/fix-codec-size.ts function fixEncoderSize(encoder, fixedBytes) { return createEncoder({ fixedSize: fixedBytes, write: (value, bytes, offset) => { const variableByteArray = encoder.encode(value); const fixedByteArray = variableByteArray.length > fixedBytes ? variableByteArray.slice(0, fixedBytes) : variableByteArray; bytes.set(fixedByteArray, offset); return offset + fixedBytes; } }); } function fixDecoderSize(decoder, fixedBytes) { return createDecoder({ fixedSize: fixedBytes, read: (bytes, offset) => { assertByteArrayHasEnoughBytesForCodec("fixCodecSize", fixedBytes, bytes, offset); if (offset > 0 || bytes.length > fixedBytes) { bytes = bytes.slice(offset, offset + fixedBytes); } if (isFixedSize(decoder)) { bytes = fixBytes(bytes, decoder.fixedSize); } const [value] = decoder.read(bytes, 0); return [value, offset + fixedBytes]; } }); } // src/transform-codec.ts function transformEncoder(encoder, unmap) { return createEncoder({ ...isVariableSize(encoder) ? { ...encoder, getSizeFromValue: (value) => encoder.getSizeFromValue(unmap(value)) } : encoder, write: (value, bytes, offset) => encoder.write(unmap(value), bytes, offset) }); } function transformDecoder(decoder, map) { return createDecoder({ ...decoder, read: (bytes, offset) => { const [value, newOffset] = decoder.read(bytes, offset); return [map(value, bytes, offset), newOffset]; } }); } // src/assertions.ts function assertValidBaseString(alphabet4, testValue, givenValue = testValue) { if (!testValue.match(new RegExp(`^[${alphabet4}]*$`))) { throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, { alphabet: alphabet4, base: alphabet4.length, value: givenValue }); } } var getBaseXEncoder = (alphabet4) => { return createEncoder({ getSizeFromValue: (value) => { const [leadingZeroes, tailChars] = partitionLeadingZeroes(value, alphabet4[0]); if (!tailChars) return value.length; const base10Number = getBigIntFromBaseX(tailChars, alphabet4); return leadingZeroes.length + Math.ceil(base10Number.toString(16).length / 2); }, write(value, bytes, offset) { assertValidBaseString(alphabet4, value); if (value === "") return offset; const [leadingZeroes, tailChars] = partitionLeadingZeroes(value, alphabet4[0]); if (!tailChars) { bytes.set(new Uint8Array(leadingZeroes.length).fill(0), offset); return offset + leadingZeroes.length; } let base10Number = getBigIntFromBaseX(tailChars, alphabet4); const tailBytes = []; while (base10Number > 0n) { tailBytes.unshift(Number(base10Number % 256n)); base10Number /= 256n; } const bytesToAdd = [...Array(leadingZeroes.length).fill(0), ...tailBytes]; bytes.set(bytesToAdd, offset); return offset + bytesToAdd.length; } }); }; var getBaseXDecoder = (alphabet4) => { return createDecoder({ read(rawBytes, offset) { const bytes = offset === 0 ? rawBytes : rawBytes.slice(offset); if (bytes.length === 0) return ["", 0]; let trailIndex = bytes.findIndex((n) => n !== 0); trailIndex = trailIndex === -1 ? bytes.length : trailIndex; const leadingZeroes = alphabet4[0].repeat(trailIndex); if (trailIndex === bytes.length) return [leadingZeroes, rawBytes.length]; const base10Number = bytes.slice(trailIndex).reduce((sum, byte) => sum * 256n + BigInt(byte), 0n); const tailChars = getBaseXFromBigInt(base10Number, alphabet4); return [leadingZeroes + tailChars, rawBytes.length]; } }); }; function partitionLeadingZeroes(value, zeroCharacter) { const [leadingZeros, tailChars] = value.split(new RegExp(`((?!${zeroCharacter}).*)`)); return [leadingZeros, tailChars]; } function getBigIntFromBaseX(value, alphabet4) { const base = BigInt(alphabet4.length); let sum = 0n; for (const char of value) { sum *= base; sum += BigInt(alphabet4.indexOf(char)); } return sum; } function getBaseXFromBigInt(value, alphabet4) { const base = BigInt(alphabet4.length); const tailChars = []; while (value > 0n) { tailChars.unshift(alphabet4[Number(value % base)]); value /= base; } return tailChars.join(""); } // src/base58.ts var alphabet2 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; var getBase58Encoder = () => getBaseXEncoder(alphabet2); var getBase58Decoder = () => getBaseXDecoder(alphabet2); // src/base64.ts var alphabet3 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; var getBase64Encoder = () => { { return createEncoder({ getSizeFromValue: (value) => Buffer.from(value, "base64").length, write(value, bytes, offset) { assertValidBaseString(alphabet3, value.replace(/=/g, "")); const buffer = Buffer.from(value, "base64"); bytes.set(buffer, offset); return buffer.length + offset; } }); } }; // src/null-characters.ts var removeNullCharacters = (value) => ( // eslint-disable-next-line no-control-regex value.replace(/\u0000/g, "") ); // ../text-encoding-impl/dist/index.node.mjs var e = globalThis.TextDecoder; var o = globalThis.TextEncoder; // src/utf8.ts var getUtf8Encoder = () => { let textEncoder; return createEncoder({ getSizeFromValue: (value) => (textEncoder ||= new o()).encode(value).length, write: (value, bytes, offset) => { const bytesToAdd = (textEncoder ||= new o()).encode(value); bytes.set(bytesToAdd, offset); return offset + bytesToAdd.length; } }); }; var getUtf8Decoder = () => { let textDecoder; return createDecoder({ read(bytes, offset) { const value = (textDecoder ||= new e()).decode(bytes.slice(offset)); return [removeNullCharacters(value), bytes.length]; } }); }; var cachedEd25519Decision; async function isEd25519CurveSupported(subtle) { if (cachedEd25519Decision === void 0) { cachedEd25519Decision = new Promise((resolve) => { subtle.generateKey( "Ed25519", /* extractable */ false, ["sign", "verify"] ).then(() => { resolve(cachedEd25519Decision = true); }).catch(() => { resolve(cachedEd25519Decision = false); }); }); } if (typeof cachedEd25519Decision === "boolean") { return cachedEd25519Decision; } else { return await cachedEd25519Decision; } } function assertDigestCapabilityIsAvailable() { if (typeof globalThis.crypto === "undefined" || typeof globalThis.crypto.subtle?.digest !== "function") { throw new SolanaError(SOLANA_ERROR__SUBTLE_CRYPTO__DIGEST_UNIMPLEMENTED); } } async function assertKeyGenerationIsAvailable() { if (typeof globalThis.crypto === "undefined" || typeof globalThis.crypto.subtle?.generateKey !== "function") { throw new SolanaError(SOLANA_ERROR__SUBTLE_CRYPTO__GENERATE_FUNCTION_UNIMPLEMENTED); } if (!await isEd25519CurveSupported(globalThis.crypto.subtle)) { throw new SolanaError(SOLANA_ERROR__SUBTLE_CRYPTO__ED25519_ALGORITHM_UNIMPLEMENTED); } } function assertKeyExporterIsAvailable() { if (typeof globalThis.crypto === "undefined" || typeof globalThis.crypto.subtle?.exportKey !== "function") { throw new SolanaError(SOLANA_ERROR__SUBTLE_CRYPTO__EXPORT_FUNCTION_UNIMPLEMENTED); } } function assertSigningCapabilityIsAvailable() { if (typeof globalThis.crypto === "undefined" || typeof globalThis.crypto.subtle?.sign !== "function") { throw new SolanaError(SOLANA_ERROR__SUBTLE_CRYPTO__SIGN_FUNCTION_UNIMPLEMENTED); } } // src/address.ts var memoizedBase58Encoder; var memoizedBase58Decoder; function getMemoizedBase58Encoder() { if (!memoizedBase58Encoder) memoizedBase58Encoder = getBase58Encoder(); return memoizedBase58Encoder; } function getMemoizedBase58Decoder() { if (!memoizedBase58Decoder) memoizedBase58Decoder = getBase58Decoder(); return memoizedBase58Decoder; } function assertIsAddress(putativeAddress) { if ( // Lowest address (32 bytes of zeroes) putativeAddress.length < 32 || // Highest address (32 bytes of 255) putativeAddress.length > 44 ) { throw new SolanaError(SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE, { actualLength: putativeAddress.length }); } const base58Encoder = getMemoizedBase58Encoder(); const bytes = base58Encoder.encode(putativeAddress); const numBytes = bytes.byteLength; if (numBytes !== 32) { throw new SolanaError(SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH, { actualLength: numBytes }); } } function address(putativeAddress) { assertIsAddress(putativeAddress); return putativeAddress; } function getAddressEncoder() { return transformEncoder( fixEncoderSize(getMemoizedBase58Encoder(), 32), (putativeAddress) => address(putativeAddress) ); } function getAddressDecoder() { return fixDecoderSize(getMemoizedBase58Decoder(), 32); } function getAddressCodec() { return combineCodec(getAddressEncoder(), getAddressDecoder()); } // src/vendor/noble/ed25519.ts var D = 37095705934669439343138083508754565189542113879843219016388785533085940283555n; var P = 57896044618658097711785492504343953926634992332820282019728792003956564819949n; var RM1 = 19681161376707505956807079304988542015446066515923890162744021073123829784752n; function mod(a) { const r = a % P; return r >= 0n ? r : P + r; } function pow2(x, power) { let r = x; while (power-- > 0n) { r *= r; r %= P; } return r; } function pow_2_252_3(x) { const x2 = x * x % P; const b2 = x2 * x % P; const b4 = pow2(b2, 2n) * b2 % P; const b5 = pow2(b4, 1n) * x % P; const b10 = pow2(b5, 5n) * b5 % P; const b20 = pow2(b10, 10n) * b10 % P; const b40 = pow2(b20, 20n) * b20 % P; const b80 = pow2(b40, 40n) * b40 % P; const b160 = pow2(b80, 80n) * b80 % P; const b240 = pow2(b160, 80n) * b80 % P; const b250 = pow2(b240, 10n) * b10 % P; const pow_p_5_8 = pow2(b250, 2n) * x % P; return pow_p_5_8; } function uvRatio(u, v) { const v3 = mod(v * v * v); const v7 = mod(v3 * v3 * v); const pow = pow_2_252_3(u * v7); let x = mod(u * v3 * pow); const vx2 = mod(v * x * x); const root1 = x; const root2 = mod(x * RM1); const useRoot1 = vx2 === u; const useRoot2 = vx2 === mod(-u); const noRoot = vx2 === mod(-u * RM1); if (useRoot1) x = root1; if (useRoot2 || noRoot) x = root2; if ((mod(x) & 1n) === 1n) x = mod(-x); if (!useRoot1 && !useRoot2) { return null; } return x; } function pointIsOnCurve(y, lastByte) { const y2 = mod(y * y); const u = mod(y2 - 1n); const v = mod(D * y2 + 1n); const x = uvRatio(u, v); if (x === null) { return false; } const isLastByteOdd = (lastByte & 128) !== 0; if (x === 0n && isLastByteOdd) { return false; } return true; } // src/curve.ts function byteToHex(byte) { const hexString = byte.toString(16); if (hexString.length === 1) { return `0${hexString}`; } else { return hexString; } } function decompressPointBytes(bytes) { const hexString = bytes.reduce((acc, byte, ii) => `${byteToHex(ii === 31 ? byte & -129 : byte)}${acc}`, ""); const integerLiteralString = `0x${hexString}`; return BigInt(integerLiteralString); } function compressedPointBytesAreOnCurve(bytes) { if (bytes.byteLength !== 32) { return false; } const y = decompressPointBytes(bytes); return pointIsOnCurve(y, bytes[31]); } var MAX_SEED_LENGTH = 32; var MAX_SEEDS = 16; var PDA_MARKER_BYTES = [ // The string 'ProgramDerivedAddress' 80, 114, 111, 103, 114, 97, 109, 68, 101, 114, 105, 118, 101, 100, 65, 100, 100, 114, 101, 115, 115 ]; async function createProgramDerivedAddress({ programAddress, seeds }) { assertDigestCapabilityIsAvailable(); if (seeds.length > MAX_SEEDS) { throw new SolanaError(SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED, { actual: seeds.length, maxSeeds: MAX_SEEDS }); } let textEncoder; const seedBytes = seeds.reduce((acc, seed, ii) => { const bytes = typeof seed === "string" ? (textEncoder ||= new TextEncoder()).encode(seed) : seed; if (bytes.byteLength > MAX_SEED_LENGTH) { throw new SolanaError(SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED, { actual: bytes.byteLength, index: ii, maxSeedLength: MAX_SEED_LENGTH }); } acc.push(...bytes); return acc; }, []); const base58EncodedAddressCodec = getAddressCodec(); const programAddressBytes = base58EncodedAddressCodec.encode(programAddress); const addressBytesBuffer = await crypto.subtle.digest( "SHA-256", new Uint8Array([...seedBytes, ...programAddressBytes, ...PDA_MARKER_BYTES]) ); const addressBytes = new Uint8Array(addressBytesBuffer); if (compressedPointBytesAreOnCurve(addressBytes)) { throw new SolanaError(SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE); } return base58EncodedAddressCodec.decode(addressBytes); } async function getProgramDerivedAddress({ programAddress, seeds }) { let bumpSeed = 255; while (bumpSeed > 0) { try { const address2 = await createProgramDerivedAddress({ programAddress, seeds: [...seeds, new Uint8Array([bumpSeed])] }); return [address2, bumpSeed]; } catch (e) { if (isSolanaError(e, SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE)) { bumpSeed--; } else { throw e; } } } throw new SolanaError(SOLANA_ERROR__ADDRESSES__FAILED_TO_FIND_VIABLE_PDA_BUMP_SEED); } async function getAddressFromPublicKey(publicKey) { assertKeyExporterIsAvailable(); if (publicKey.type !== "public" || publicKey.algorithm.name !== "Ed25519") { throw new SolanaError(SOLANA_ERROR__ADDRESSES__INVALID_ED25519_PUBLIC_KEY); } const publicKeyBytes = await crypto.subtle.exportKey("raw", publicKey); return getAddressDecoder().decode(new Uint8Array(publicKeyBytes)); } /** * PoD Protocol Program ID on Solana Devnet */ const PROGRAM_ID = address("HEpGLgYsE1kP8aoYKyLFc3JVVrofS7T4zEA6fWBJsZps"); /** * Message types supported by PoD Protocol */ var MessageType; (function (MessageType) { MessageType[MessageType["TEXT"] = 0] = "TEXT"; MessageType[MessageType["IMAGE"] = 1] = "IMAGE"; MessageType[MessageType["CODE"] = 2] = "CODE"; MessageType[MessageType["FILE"] = 3] = "FILE"; })(MessageType || (MessageType = {})); /** * Message status in the delivery lifecycle */ var MessageStatus; (function (MessageStatus) { MessageStatus["PENDING"] = "pending"; MessageStatus["DELIVERED"] = "delivered"; MessageStatus["READ"] = "read"; MessageStatus["FAILED"] = "failed"; })(MessageStatus || (MessageStatus = {})); /** * Channel visibility options */ var ChannelVisibility; (function (ChannelVisibility) { ChannelVisibility[ChannelVisibility["Public"] = 0] = "Public"; ChannelVisibility[ChannelVisibility["Private"] = 1] = "Private"; ChannelVisibility[ChannelVisibility["Restricted"] = 2] = "Restricted"; })(ChannelVisibility || (ChannelVisibility = {})); /** * Agent capabilities as bitmask values */ const AGENT_CAPABILITIES = { TEXT: 1, IMAGE: 2, CODE: 4, ANALYSIS: 8, TRADING: 16, DATA_PROCESSING: 32, CONTENT_GENERATION: 64, CUSTOM1: 128, CUSTOM2: 256, }; /** * Error types returned by PoD Protocol program */ var PodComError; (function (PodComError) { PodComError[PodComError["InvalidMetadataUriLength"] = 6000] = "InvalidMetadataUriLength"; PodComError[PodComError["Unauthorized"] = 6001] = "Unauthorized"; PodComError[PodComError["MessageExpired"] = 6002] = "MessageExpired"; PodComError[PodComError["InvalidMessageStatusTransition"] = 6003] = "InvalidMessageStatusTransition"; PodComError[PodComError["InsufficientAccounts"] = 6004] = "InsufficientAccounts"; PodComError[PodComError["InvalidAccountData"] = 6005] = "InvalidAccountData"; PodComError[PodComError["InvalidInstructionData"] = 6006] = "InvalidInstructionData"; })(PodComError || (PodComError = {})); /** * SDK Error codes */ var ErrorCode; (function (ErrorCode) { ErrorCode["PROGRAM_ERROR"] = "PROGRAM_ERROR"; ErrorCode["NETWORK_ERROR"] = "NETWORK_ERROR"; ErrorCode["RPC_ERROR"] = "RPC_ERROR"; ErrorCode["ACCOUNT_ERROR"] = "ACCOUNT_ERROR"; ErrorCode["ACCOUNT_NOT_FOUND"] = "ACCOUNT_NOT_FOUND"; ErrorCode["INVALID_ACCOUNT_DATA"] = "INVALID_ACCOUNT_DATA"; ErrorCode["TRANSACTION_ERROR"] = "TRANSACTION_ERROR"; ErrorCode["VALIDATION_ERROR"] = "VALIDATION_ERROR"; ErrorCode["TIMEOUT_ERROR"] = "TIMEOUT_ERROR"; ErrorCode["RATE_LIMIT_ERROR"] = "RATE_LIMIT_ERROR"; ErrorCode["INSUFFICIENT_DATA"] = "INSUFFICIENT_DATA"; })(ErrorCode || (ErrorCode = {})); export { SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE as $, getAddressEncoder as A, addEncoderSizePrefix as B, getUtf8Encoder as C, getAddressDecoder as D, addDecoderSizePrefix as E, getUtf8Decoder as F, combineCodec as G, getProgramDerivedAddress as H, MessageStatus as I, ChannelVisibility as J, AGENT_CAPABILITIES as K, PodComError as L, MessageType as M, ErrorCode as N, address as O, PROGRAM_ID as P, assertKeyGenerationIsAvailable as Q, assertSigningCapabilityIsAvailable as R, SolanaError as S, getAddressFromPublicKey as T, SOLANA_ERROR__TRANSACTION__ADDRESSES_CANNOT_SIGN_TRANSACTION as U, SOLANA_ERROR__RPC__API_PLAN_MISSING_FOR_RPC_METHOD as V, getSolanaErrorFromJsonRpcError as W, SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR as X, SOLANA_ERROR__RPC__INTEGER_OVERFLOW as Y, safeCaptureStackTrace as Z, SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING as _, SOLANA_ERROR__ACCOUNTS__FAILED_TO_DECODE_ACCOUNT as a, SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN as a0, SOLANA_ERROR__RPC_SUBSCRIPTIONS__EXPECTED_SERVER_SUBSCRIPTION_ID as a1, SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED as a2, SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED as a3, SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT as a4, SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CLOSED_BEFORE_MESSAGE_BUFFERED as a5, SOLANA_ERROR__ACCOUNTS__ACCOUNT_NOT_FOUND as b, SOLANA_ERROR__ACCOUNTS__ONE_OR_MORE_ACCOUNTS_NOT_FOUND as c, createEncoder as d, createDecoder as e, SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE as f, getBase64Encoder as g, assertByteArrayIsNotEmptyForCodec as h, assertByteArrayHasEnoughBytesForCodec as i, getEncodedSize as j, transformDecoder as k, SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS as l, SOLANA_ERROR__CODECS__INVALID_ENUM_VARIANT as m, isFixedSize as n, SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS as o, containsBytes as p, SOLANA_ERROR__CODECS__INVALID_CONSTANT as q, SOLANA_ERROR__CODECS__UNION_VARIANT_OUT_OF_RANGE as r, SOLANA_ERROR__CODECS__INVALID_DISCRIMINATED_UNION_VARIANT as s, transformEncoder as t, SOLANA_ERROR__CODECS__ENUM_DISCRIMINATOR_OUT_OF_RANGE as u, assertIsFixedSize as v, fixEncoderSize as w, fixDecoderSize as x, isSolanaError as y, SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM as z }; //# sourceMappingURL=types-CllXlTfL.js.map