@kwespay/widget 1.0.3 → 1.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -805,3045 +805,6 @@ class WalletService {
805
805
  }
806
806
  }
807
807
 
808
- class KwesPayError extends Error {
809
- constructor(message, code, cause) {
810
- super(message);
811
- this.name = "KwesPayError";
812
- this.code = code;
813
- this.cause = cause;
814
- }
815
- }
816
-
817
- const ENDPOINT = "https://d502-154-161-98-26.ngrok-free.app/graphql";
818
- const TESTNET_CONTRACTS = {
819
- sepolia: "0x39bE436D6A34d0990cb71c9cBD24a5361d85e00B",
820
- baseSepolia: "0x7515b1b1BcA33E7a9ccBd5E2b93771884654De77",
821
- polygonAmoy: "0xD31dF3eBd220Fd3e190A346F8927819295d28980",
822
- liskTestnet: "0xd04A78a998146EBAD04c2b68E020C06Dc3b3717f",
823
- };
824
- const MAINNET_CONTRACTS = {
825
- // lisk: "0x...",
826
- };
827
- const CONTRACT_ADDRESSES = {
828
- ...TESTNET_CONTRACTS,
829
- ...MAINNET_CONTRACTS,
830
- };
831
- function resolveContractAddress(network) {
832
- const addr = CONTRACT_ADDRESSES[network];
833
- if (!addr)
834
- throw new Error(`No contract deployed on network: ${network}`);
835
- return addr;
836
- }
837
-
838
- async function gqlRequest(query, variables, apiKey) {
839
- const headers = {
840
- "Content-Type": "application/json",
841
- };
842
- if (apiKey)
843
- headers["X-API-Key"] = apiKey;
844
- let response;
845
- try {
846
- response = await fetch(ENDPOINT, {
847
- method: "POST",
848
- headers,
849
- body: JSON.stringify({ query, variables }),
850
- });
851
- }
852
- catch (err) {
853
- throw new KwesPayError("Network request failed — check your connectivity", "NETWORK_ERROR", err);
854
- }
855
- if (!response.ok) {
856
- throw new KwesPayError(`HTTP ${response.status}: ${response.statusText}`, "NETWORK_ERROR");
857
- }
858
- const json = await response.json();
859
- if (json.errors?.length) {
860
- throw new KwesPayError(json.errors[0]?.message ?? "GraphQL error", "UNKNOWN");
861
- }
862
- if (!json.data) {
863
- throw new KwesPayError("Empty response from server", "UNKNOWN");
864
- }
865
- return json.data;
866
- }
867
-
868
- const GQL_VALIDATE_KEY = `
869
- query ValidateAccessKey($accessKey: String!) {
870
- validateAccessKey(accessKey: $accessKey) {
871
- isValid
872
- keyId
873
- keyLabel
874
- activeFlag
875
- expirationDate
876
- vendorInfo {
877
- vendorPk
878
- vendorIdentifier
879
- businessName
880
- }
881
- allowedVendors
882
- allowedNetworks
883
- allowedTokens
884
- error
885
- }
886
- }
887
- `;
888
- const GQL_CREATE_QUOTE = `
889
- mutation CreateQuote($input: CreateQuoteInput!) {
890
- createQuote(input: $input) {
891
- success
892
- message
893
- quoteId
894
- quoteReference
895
- cryptoCurrency
896
- tokenAddress
897
- amountBaseUnits
898
- displayAmount
899
- network
900
- chainId
901
- expiresAt
902
- }
903
- }
904
- `;
905
- const GQL_CREATE_TRANSACTION = `
906
- mutation CreateTransaction($input: CreateTransactionInput!) {
907
- createTransaction(input: $input) {
908
- success
909
- message
910
- paymentIdBytes32
911
- backendSignature
912
- tokenAddress
913
- amountBaseUnits
914
- chainId
915
- expiresAt
916
- transaction {
917
- transactionReference
918
- transactionStatus
919
- }
920
- }
921
- }
922
- `;
923
- const GQL_TRANSACTION_STATUS = `
924
- query GetTransactionStatus($transactionReference: String!) {
925
- getTransactionStatus(transactionReference: $transactionReference) {
926
- transactionReference
927
- transactionStatus
928
- blockchainHash
929
- blockchainNetwork
930
- displayAmount
931
- cryptoCurrency
932
- payerWalletAddress
933
- initiatedAt
934
- }
935
- }
936
- `;
937
-
938
- const version$1 = '1.2.3';
939
-
940
- let BaseError$1 = class BaseError extends Error {
941
- constructor(shortMessage, args = {}) {
942
- const details = args.cause instanceof BaseError
943
- ? args.cause.details
944
- : args.cause?.message
945
- ? args.cause.message
946
- : args.details;
947
- const docsPath = args.cause instanceof BaseError
948
- ? args.cause.docsPath || args.docsPath
949
- : args.docsPath;
950
- const message = [
951
- shortMessage || 'An error occurred.',
952
- '',
953
- ...(args.metaMessages ? [...args.metaMessages, ''] : []),
954
- ...(docsPath ? [`Docs: https://abitype.dev${docsPath}`] : []),
955
- ...(details ? [`Details: ${details}`] : []),
956
- `Version: abitype@${version$1}`,
957
- ].join('\n');
958
- super(message);
959
- Object.defineProperty(this, "details", {
960
- enumerable: true,
961
- configurable: true,
962
- writable: true,
963
- value: void 0
964
- });
965
- Object.defineProperty(this, "docsPath", {
966
- enumerable: true,
967
- configurable: true,
968
- writable: true,
969
- value: void 0
970
- });
971
- Object.defineProperty(this, "metaMessages", {
972
- enumerable: true,
973
- configurable: true,
974
- writable: true,
975
- value: void 0
976
- });
977
- Object.defineProperty(this, "shortMessage", {
978
- enumerable: true,
979
- configurable: true,
980
- writable: true,
981
- value: void 0
982
- });
983
- Object.defineProperty(this, "name", {
984
- enumerable: true,
985
- configurable: true,
986
- writable: true,
987
- value: 'AbiTypeError'
988
- });
989
- if (args.cause)
990
- this.cause = args.cause;
991
- this.details = details;
992
- this.docsPath = docsPath;
993
- this.metaMessages = args.metaMessages;
994
- this.shortMessage = shortMessage;
995
- }
996
- };
997
-
998
- // TODO: This looks cool. Need to check the performance of `new RegExp` versus defined inline though.
999
- // https://twitter.com/GabrielVergnaud/status/1622906834343366657
1000
- function execTyped(regex, string) {
1001
- const match = regex.exec(string);
1002
- return match?.groups;
1003
- }
1004
- // `bytes<M>`: binary type of `M` bytes, `0 < M <= 32`
1005
- // https://regexr.com/6va55
1006
- const bytesRegex = /^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/;
1007
- // `(u)int<M>`: (un)signed integer type of `M` bits, `0 < M <= 256`, `M % 8 == 0`
1008
- // https://regexr.com/6v8hp
1009
- const integerRegex$1 = /^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/;
1010
- const isTupleRegex = /^\(.+?\).*?$/;
1011
-
1012
- // https://regexr.com/7f7rv
1013
- const tupleRegex = /^tuple(?<array>(\[(\d*)\])*)$/;
1014
- /**
1015
- * Formats {@link AbiParameter} to human-readable ABI parameter.
1016
- *
1017
- * @param abiParameter - ABI parameter
1018
- * @returns Human-readable ABI parameter
1019
- *
1020
- * @example
1021
- * const result = formatAbiParameter({ type: 'address', name: 'from' })
1022
- * // ^? const result: 'address from'
1023
- */
1024
- function formatAbiParameter(abiParameter) {
1025
- let type = abiParameter.type;
1026
- if (tupleRegex.test(abiParameter.type) && 'components' in abiParameter) {
1027
- type = '(';
1028
- const length = abiParameter.components.length;
1029
- for (let i = 0; i < length; i++) {
1030
- const component = abiParameter.components[i];
1031
- type += formatAbiParameter(component);
1032
- if (i < length - 1)
1033
- type += ', ';
1034
- }
1035
- const result = execTyped(tupleRegex, abiParameter.type);
1036
- type += `)${result?.array || ''}`;
1037
- return formatAbiParameter({
1038
- ...abiParameter,
1039
- type,
1040
- });
1041
- }
1042
- // Add `indexed` to type if in `abiParameter`
1043
- if ('indexed' in abiParameter && abiParameter.indexed)
1044
- type = `${type} indexed`;
1045
- // Return human-readable ABI parameter
1046
- if (abiParameter.name)
1047
- return `${type} ${abiParameter.name}`;
1048
- return type;
1049
- }
1050
-
1051
- /**
1052
- * Formats {@link AbiParameter}s to human-readable ABI parameters.
1053
- *
1054
- * @param abiParameters - ABI parameters
1055
- * @returns Human-readable ABI parameters
1056
- *
1057
- * @example
1058
- * const result = formatAbiParameters([
1059
- * // ^? const result: 'address from, uint256 tokenId'
1060
- * { type: 'address', name: 'from' },
1061
- * { type: 'uint256', name: 'tokenId' },
1062
- * ])
1063
- */
1064
- function formatAbiParameters(abiParameters) {
1065
- let params = '';
1066
- const length = abiParameters.length;
1067
- for (let i = 0; i < length; i++) {
1068
- const abiParameter = abiParameters[i];
1069
- params += formatAbiParameter(abiParameter);
1070
- if (i !== length - 1)
1071
- params += ', ';
1072
- }
1073
- return params;
1074
- }
1075
-
1076
- /**
1077
- * Formats ABI item (e.g. error, event, function) into human-readable ABI item
1078
- *
1079
- * @param abiItem - ABI item
1080
- * @returns Human-readable ABI item
1081
- */
1082
- function formatAbiItem$1(abiItem) {
1083
- if (abiItem.type === 'function')
1084
- return `function ${abiItem.name}(${formatAbiParameters(abiItem.inputs)})${abiItem.stateMutability && abiItem.stateMutability !== 'nonpayable'
1085
- ? ` ${abiItem.stateMutability}`
1086
- : ''}${abiItem.outputs?.length
1087
- ? ` returns (${formatAbiParameters(abiItem.outputs)})`
1088
- : ''}`;
1089
- if (abiItem.type === 'event')
1090
- return `event ${abiItem.name}(${formatAbiParameters(abiItem.inputs)})`;
1091
- if (abiItem.type === 'error')
1092
- return `error ${abiItem.name}(${formatAbiParameters(abiItem.inputs)})`;
1093
- if (abiItem.type === 'constructor')
1094
- return `constructor(${formatAbiParameters(abiItem.inputs)})${abiItem.stateMutability === 'payable' ? ' payable' : ''}`;
1095
- if (abiItem.type === 'fallback')
1096
- return `fallback() external${abiItem.stateMutability === 'payable' ? ' payable' : ''}`;
1097
- return 'receive() external payable';
1098
- }
1099
-
1100
- // https://regexr.com/7gmok
1101
- const errorSignatureRegex = /^error (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)$/;
1102
- function isErrorSignature(signature) {
1103
- return errorSignatureRegex.test(signature);
1104
- }
1105
- function execErrorSignature(signature) {
1106
- return execTyped(errorSignatureRegex, signature);
1107
- }
1108
- // https://regexr.com/7gmoq
1109
- const eventSignatureRegex = /^event (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)$/;
1110
- function isEventSignature(signature) {
1111
- return eventSignatureRegex.test(signature);
1112
- }
1113
- function execEventSignature(signature) {
1114
- return execTyped(eventSignatureRegex, signature);
1115
- }
1116
- // https://regexr.com/7gmot
1117
- const functionSignatureRegex = /^function (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)(?: (?<scope>external|public{1}))?(?: (?<stateMutability>pure|view|nonpayable|payable{1}))?(?: returns\s?\((?<returns>.*?)\))?$/;
1118
- function isFunctionSignature(signature) {
1119
- return functionSignatureRegex.test(signature);
1120
- }
1121
- function execFunctionSignature(signature) {
1122
- return execTyped(functionSignatureRegex, signature);
1123
- }
1124
- // https://regexr.com/7gmp3
1125
- const structSignatureRegex = /^struct (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*) \{(?<properties>.*?)\}$/;
1126
- function isStructSignature(signature) {
1127
- return structSignatureRegex.test(signature);
1128
- }
1129
- function execStructSignature(signature) {
1130
- return execTyped(structSignatureRegex, signature);
1131
- }
1132
- // https://regexr.com/78u01
1133
- const constructorSignatureRegex = /^constructor\((?<parameters>.*?)\)(?:\s(?<stateMutability>payable{1}))?$/;
1134
- function isConstructorSignature(signature) {
1135
- return constructorSignatureRegex.test(signature);
1136
- }
1137
- function execConstructorSignature(signature) {
1138
- return execTyped(constructorSignatureRegex, signature);
1139
- }
1140
- // https://regexr.com/7srtn
1141
- const fallbackSignatureRegex = /^fallback\(\) external(?:\s(?<stateMutability>payable{1}))?$/;
1142
- function isFallbackSignature(signature) {
1143
- return fallbackSignatureRegex.test(signature);
1144
- }
1145
- function execFallbackSignature(signature) {
1146
- return execTyped(fallbackSignatureRegex, signature);
1147
- }
1148
- // https://regexr.com/78u1k
1149
- const receiveSignatureRegex = /^receive\(\) external payable$/;
1150
- function isReceiveSignature(signature) {
1151
- return receiveSignatureRegex.test(signature);
1152
- }
1153
- const eventModifiers = new Set(['indexed']);
1154
- const functionModifiers = new Set([
1155
- 'calldata',
1156
- 'memory',
1157
- 'storage',
1158
- ]);
1159
-
1160
- class UnknownTypeError extends BaseError$1 {
1161
- constructor({ type }) {
1162
- super('Unknown type.', {
1163
- metaMessages: [
1164
- `Type "${type}" is not a valid ABI type. Perhaps you forgot to include a struct signature?`,
1165
- ],
1166
- });
1167
- Object.defineProperty(this, "name", {
1168
- enumerable: true,
1169
- configurable: true,
1170
- writable: true,
1171
- value: 'UnknownTypeError'
1172
- });
1173
- }
1174
- }
1175
- class UnknownSolidityTypeError extends BaseError$1 {
1176
- constructor({ type }) {
1177
- super('Unknown type.', {
1178
- metaMessages: [`Type "${type}" is not a valid ABI type.`],
1179
- });
1180
- Object.defineProperty(this, "name", {
1181
- enumerable: true,
1182
- configurable: true,
1183
- writable: true,
1184
- value: 'UnknownSolidityTypeError'
1185
- });
1186
- }
1187
- }
1188
-
1189
- class InvalidParameterError extends BaseError$1 {
1190
- constructor({ param }) {
1191
- super('Invalid ABI parameter.', {
1192
- details: param,
1193
- });
1194
- Object.defineProperty(this, "name", {
1195
- enumerable: true,
1196
- configurable: true,
1197
- writable: true,
1198
- value: 'InvalidParameterError'
1199
- });
1200
- }
1201
- }
1202
- class SolidityProtectedKeywordError extends BaseError$1 {
1203
- constructor({ param, name }) {
1204
- super('Invalid ABI parameter.', {
1205
- details: param,
1206
- metaMessages: [
1207
- `"${name}" is a protected Solidity keyword. More info: https://docs.soliditylang.org/en/latest/cheatsheet.html`,
1208
- ],
1209
- });
1210
- Object.defineProperty(this, "name", {
1211
- enumerable: true,
1212
- configurable: true,
1213
- writable: true,
1214
- value: 'SolidityProtectedKeywordError'
1215
- });
1216
- }
1217
- }
1218
- class InvalidModifierError extends BaseError$1 {
1219
- constructor({ param, type, modifier, }) {
1220
- super('Invalid ABI parameter.', {
1221
- details: param,
1222
- metaMessages: [
1223
- `Modifier "${modifier}" not allowed${type ? ` in "${type}" type` : ''}.`,
1224
- ],
1225
- });
1226
- Object.defineProperty(this, "name", {
1227
- enumerable: true,
1228
- configurable: true,
1229
- writable: true,
1230
- value: 'InvalidModifierError'
1231
- });
1232
- }
1233
- }
1234
- class InvalidFunctionModifierError extends BaseError$1 {
1235
- constructor({ param, type, modifier, }) {
1236
- super('Invalid ABI parameter.', {
1237
- details: param,
1238
- metaMessages: [
1239
- `Modifier "${modifier}" not allowed${type ? ` in "${type}" type` : ''}.`,
1240
- `Data location can only be specified for array, struct, or mapping types, but "${modifier}" was given.`,
1241
- ],
1242
- });
1243
- Object.defineProperty(this, "name", {
1244
- enumerable: true,
1245
- configurable: true,
1246
- writable: true,
1247
- value: 'InvalidFunctionModifierError'
1248
- });
1249
- }
1250
- }
1251
- class InvalidAbiTypeParameterError extends BaseError$1 {
1252
- constructor({ abiParameter, }) {
1253
- super('Invalid ABI parameter.', {
1254
- details: JSON.stringify(abiParameter, null, 2),
1255
- metaMessages: ['ABI parameter type is invalid.'],
1256
- });
1257
- Object.defineProperty(this, "name", {
1258
- enumerable: true,
1259
- configurable: true,
1260
- writable: true,
1261
- value: 'InvalidAbiTypeParameterError'
1262
- });
1263
- }
1264
- }
1265
-
1266
- class InvalidSignatureError extends BaseError$1 {
1267
- constructor({ signature, type, }) {
1268
- super(`Invalid ${type} signature.`, {
1269
- details: signature,
1270
- });
1271
- Object.defineProperty(this, "name", {
1272
- enumerable: true,
1273
- configurable: true,
1274
- writable: true,
1275
- value: 'InvalidSignatureError'
1276
- });
1277
- }
1278
- }
1279
- class UnknownSignatureError extends BaseError$1 {
1280
- constructor({ signature }) {
1281
- super('Unknown signature.', {
1282
- details: signature,
1283
- });
1284
- Object.defineProperty(this, "name", {
1285
- enumerable: true,
1286
- configurable: true,
1287
- writable: true,
1288
- value: 'UnknownSignatureError'
1289
- });
1290
- }
1291
- }
1292
- class InvalidStructSignatureError extends BaseError$1 {
1293
- constructor({ signature }) {
1294
- super('Invalid struct signature.', {
1295
- details: signature,
1296
- metaMessages: ['No properties exist.'],
1297
- });
1298
- Object.defineProperty(this, "name", {
1299
- enumerable: true,
1300
- configurable: true,
1301
- writable: true,
1302
- value: 'InvalidStructSignatureError'
1303
- });
1304
- }
1305
- }
1306
-
1307
- class CircularReferenceError extends BaseError$1 {
1308
- constructor({ type }) {
1309
- super('Circular reference detected.', {
1310
- metaMessages: [`Struct "${type}" is a circular reference.`],
1311
- });
1312
- Object.defineProperty(this, "name", {
1313
- enumerable: true,
1314
- configurable: true,
1315
- writable: true,
1316
- value: 'CircularReferenceError'
1317
- });
1318
- }
1319
- }
1320
-
1321
- class InvalidParenthesisError extends BaseError$1 {
1322
- constructor({ current, depth }) {
1323
- super('Unbalanced parentheses.', {
1324
- metaMessages: [
1325
- `"${current.trim()}" has too many ${depth > 0 ? 'opening' : 'closing'} parentheses.`,
1326
- ],
1327
- details: `Depth "${depth}"`,
1328
- });
1329
- Object.defineProperty(this, "name", {
1330
- enumerable: true,
1331
- configurable: true,
1332
- writable: true,
1333
- value: 'InvalidParenthesisError'
1334
- });
1335
- }
1336
- }
1337
-
1338
- /**
1339
- * Gets {@link parameterCache} cache key namespaced by {@link type} and {@link structs}. This prevents parameters from being accessible to types that don't allow them (e.g. `string indexed foo` not allowed outside of `type: 'event'`) and ensures different struct definitions with the same name are cached separately.
1340
- * @param param ABI parameter string
1341
- * @param type ABI parameter type
1342
- * @param structs Struct definitions to include in cache key
1343
- * @returns Cache key for {@link parameterCache}
1344
- */
1345
- function getParameterCacheKey(param, type, structs) {
1346
- let structKey = '';
1347
- if (structs)
1348
- for (const struct of Object.entries(structs)) {
1349
- if (!struct)
1350
- continue;
1351
- let propertyKey = '';
1352
- for (const property of struct[1]) {
1353
- propertyKey += `[${property.type}${property.name ? `:${property.name}` : ''}]`;
1354
- }
1355
- structKey += `(${struct[0]}{${propertyKey}})`;
1356
- }
1357
- if (type)
1358
- return `${type}:${param}${structKey}`;
1359
- return `${param}${structKey}`;
1360
- }
1361
- /**
1362
- * Basic cache seeded with common ABI parameter strings.
1363
- *
1364
- * **Note: When seeding more parameters, make sure you benchmark performance. The current number is the ideal balance between performance and having an already existing cache.**
1365
- */
1366
- const parameterCache = new Map([
1367
- // Unnamed
1368
- ['address', { type: 'address' }],
1369
- ['bool', { type: 'bool' }],
1370
- ['bytes', { type: 'bytes' }],
1371
- ['bytes32', { type: 'bytes32' }],
1372
- ['int', { type: 'int256' }],
1373
- ['int256', { type: 'int256' }],
1374
- ['string', { type: 'string' }],
1375
- ['uint', { type: 'uint256' }],
1376
- ['uint8', { type: 'uint8' }],
1377
- ['uint16', { type: 'uint16' }],
1378
- ['uint24', { type: 'uint24' }],
1379
- ['uint32', { type: 'uint32' }],
1380
- ['uint64', { type: 'uint64' }],
1381
- ['uint96', { type: 'uint96' }],
1382
- ['uint112', { type: 'uint112' }],
1383
- ['uint160', { type: 'uint160' }],
1384
- ['uint192', { type: 'uint192' }],
1385
- ['uint256', { type: 'uint256' }],
1386
- // Named
1387
- ['address owner', { type: 'address', name: 'owner' }],
1388
- ['address to', { type: 'address', name: 'to' }],
1389
- ['bool approved', { type: 'bool', name: 'approved' }],
1390
- ['bytes _data', { type: 'bytes', name: '_data' }],
1391
- ['bytes data', { type: 'bytes', name: 'data' }],
1392
- ['bytes signature', { type: 'bytes', name: 'signature' }],
1393
- ['bytes32 hash', { type: 'bytes32', name: 'hash' }],
1394
- ['bytes32 r', { type: 'bytes32', name: 'r' }],
1395
- ['bytes32 root', { type: 'bytes32', name: 'root' }],
1396
- ['bytes32 s', { type: 'bytes32', name: 's' }],
1397
- ['string name', { type: 'string', name: 'name' }],
1398
- ['string symbol', { type: 'string', name: 'symbol' }],
1399
- ['string tokenURI', { type: 'string', name: 'tokenURI' }],
1400
- ['uint tokenId', { type: 'uint256', name: 'tokenId' }],
1401
- ['uint8 v', { type: 'uint8', name: 'v' }],
1402
- ['uint256 balance', { type: 'uint256', name: 'balance' }],
1403
- ['uint256 tokenId', { type: 'uint256', name: 'tokenId' }],
1404
- ['uint256 value', { type: 'uint256', name: 'value' }],
1405
- // Indexed
1406
- [
1407
- 'event:address indexed from',
1408
- { type: 'address', name: 'from', indexed: true },
1409
- ],
1410
- ['event:address indexed to', { type: 'address', name: 'to', indexed: true }],
1411
- [
1412
- 'event:uint indexed tokenId',
1413
- { type: 'uint256', name: 'tokenId', indexed: true },
1414
- ],
1415
- [
1416
- 'event:uint256 indexed tokenId',
1417
- { type: 'uint256', name: 'tokenId', indexed: true },
1418
- ],
1419
- ]);
1420
-
1421
- function parseSignature(signature, structs = {}) {
1422
- if (isFunctionSignature(signature))
1423
- return parseFunctionSignature(signature, structs);
1424
- if (isEventSignature(signature))
1425
- return parseEventSignature(signature, structs);
1426
- if (isErrorSignature(signature))
1427
- return parseErrorSignature(signature, structs);
1428
- if (isConstructorSignature(signature))
1429
- return parseConstructorSignature(signature, structs);
1430
- if (isFallbackSignature(signature))
1431
- return parseFallbackSignature(signature);
1432
- if (isReceiveSignature(signature))
1433
- return {
1434
- type: 'receive',
1435
- stateMutability: 'payable',
1436
- };
1437
- throw new UnknownSignatureError({ signature });
1438
- }
1439
- function parseFunctionSignature(signature, structs = {}) {
1440
- const match = execFunctionSignature(signature);
1441
- if (!match)
1442
- throw new InvalidSignatureError({ signature, type: 'function' });
1443
- const inputParams = splitParameters(match.parameters);
1444
- const inputs = [];
1445
- const inputLength = inputParams.length;
1446
- for (let i = 0; i < inputLength; i++) {
1447
- inputs.push(parseAbiParameter(inputParams[i], {
1448
- modifiers: functionModifiers,
1449
- structs,
1450
- type: 'function',
1451
- }));
1452
- }
1453
- const outputs = [];
1454
- if (match.returns) {
1455
- const outputParams = splitParameters(match.returns);
1456
- const outputLength = outputParams.length;
1457
- for (let i = 0; i < outputLength; i++) {
1458
- outputs.push(parseAbiParameter(outputParams[i], {
1459
- modifiers: functionModifiers,
1460
- structs,
1461
- type: 'function',
1462
- }));
1463
- }
1464
- }
1465
- return {
1466
- name: match.name,
1467
- type: 'function',
1468
- stateMutability: match.stateMutability ?? 'nonpayable',
1469
- inputs,
1470
- outputs,
1471
- };
1472
- }
1473
- function parseEventSignature(signature, structs = {}) {
1474
- const match = execEventSignature(signature);
1475
- if (!match)
1476
- throw new InvalidSignatureError({ signature, type: 'event' });
1477
- const params = splitParameters(match.parameters);
1478
- const abiParameters = [];
1479
- const length = params.length;
1480
- for (let i = 0; i < length; i++)
1481
- abiParameters.push(parseAbiParameter(params[i], {
1482
- modifiers: eventModifiers,
1483
- structs,
1484
- type: 'event',
1485
- }));
1486
- return { name: match.name, type: 'event', inputs: abiParameters };
1487
- }
1488
- function parseErrorSignature(signature, structs = {}) {
1489
- const match = execErrorSignature(signature);
1490
- if (!match)
1491
- throw new InvalidSignatureError({ signature, type: 'error' });
1492
- const params = splitParameters(match.parameters);
1493
- const abiParameters = [];
1494
- const length = params.length;
1495
- for (let i = 0; i < length; i++)
1496
- abiParameters.push(parseAbiParameter(params[i], { structs, type: 'error' }));
1497
- return { name: match.name, type: 'error', inputs: abiParameters };
1498
- }
1499
- function parseConstructorSignature(signature, structs = {}) {
1500
- const match = execConstructorSignature(signature);
1501
- if (!match)
1502
- throw new InvalidSignatureError({ signature, type: 'constructor' });
1503
- const params = splitParameters(match.parameters);
1504
- const abiParameters = [];
1505
- const length = params.length;
1506
- for (let i = 0; i < length; i++)
1507
- abiParameters.push(parseAbiParameter(params[i], { structs, type: 'constructor' }));
1508
- return {
1509
- type: 'constructor',
1510
- stateMutability: match.stateMutability ?? 'nonpayable',
1511
- inputs: abiParameters,
1512
- };
1513
- }
1514
- function parseFallbackSignature(signature) {
1515
- const match = execFallbackSignature(signature);
1516
- if (!match)
1517
- throw new InvalidSignatureError({ signature, type: 'fallback' });
1518
- return {
1519
- type: 'fallback',
1520
- stateMutability: match.stateMutability ?? 'nonpayable',
1521
- };
1522
- }
1523
- const abiParameterWithoutTupleRegex = /^(?<type>[a-zA-Z$_][a-zA-Z0-9$_]*(?:\spayable)?)(?<array>(?:\[\d*?\])+?)?(?:\s(?<modifier>calldata|indexed|memory|storage{1}))?(?:\s(?<name>[a-zA-Z$_][a-zA-Z0-9$_]*))?$/;
1524
- const abiParameterWithTupleRegex = /^\((?<type>.+?)\)(?<array>(?:\[\d*?\])+?)?(?:\s(?<modifier>calldata|indexed|memory|storage{1}))?(?:\s(?<name>[a-zA-Z$_][a-zA-Z0-9$_]*))?$/;
1525
- const dynamicIntegerRegex = /^u?int$/;
1526
- function parseAbiParameter(param, options) {
1527
- // optional namespace cache by `type`
1528
- const parameterCacheKey = getParameterCacheKey(param, options?.type, options?.structs);
1529
- if (parameterCache.has(parameterCacheKey))
1530
- return parameterCache.get(parameterCacheKey);
1531
- const isTuple = isTupleRegex.test(param);
1532
- const match = execTyped(isTuple ? abiParameterWithTupleRegex : abiParameterWithoutTupleRegex, param);
1533
- if (!match)
1534
- throw new InvalidParameterError({ param });
1535
- if (match.name && isSolidityKeyword(match.name))
1536
- throw new SolidityProtectedKeywordError({ param, name: match.name });
1537
- const name = match.name ? { name: match.name } : {};
1538
- const indexed = match.modifier === 'indexed' ? { indexed: true } : {};
1539
- const structs = options?.structs ?? {};
1540
- let type;
1541
- let components = {};
1542
- if (isTuple) {
1543
- type = 'tuple';
1544
- const params = splitParameters(match.type);
1545
- const components_ = [];
1546
- const length = params.length;
1547
- for (let i = 0; i < length; i++) {
1548
- // remove `modifiers` from `options` to prevent from being added to tuple components
1549
- components_.push(parseAbiParameter(params[i], { structs }));
1550
- }
1551
- components = { components: components_ };
1552
- }
1553
- else if (match.type in structs) {
1554
- type = 'tuple';
1555
- components = { components: structs[match.type] };
1556
- }
1557
- else if (dynamicIntegerRegex.test(match.type)) {
1558
- type = `${match.type}256`;
1559
- }
1560
- else if (match.type === 'address payable') {
1561
- type = 'address';
1562
- }
1563
- else {
1564
- type = match.type;
1565
- if (!(options?.type === 'struct') && !isSolidityType(type))
1566
- throw new UnknownSolidityTypeError({ type });
1567
- }
1568
- if (match.modifier) {
1569
- // Check if modifier exists, but is not allowed (e.g. `indexed` in `functionModifiers`)
1570
- if (!options?.modifiers?.has?.(match.modifier))
1571
- throw new InvalidModifierError({
1572
- param,
1573
- type: options?.type,
1574
- modifier: match.modifier,
1575
- });
1576
- // Check if resolved `type` is valid if there is a function modifier
1577
- if (functionModifiers.has(match.modifier) &&
1578
- !isValidDataLocation(type, !!match.array))
1579
- throw new InvalidFunctionModifierError({
1580
- param,
1581
- type: options?.type,
1582
- modifier: match.modifier,
1583
- });
1584
- }
1585
- const abiParameter = {
1586
- type: `${type}${match.array ?? ''}`,
1587
- ...name,
1588
- ...indexed,
1589
- ...components,
1590
- };
1591
- parameterCache.set(parameterCacheKey, abiParameter);
1592
- return abiParameter;
1593
- }
1594
- // s/o latika for this
1595
- function splitParameters(params, result = [], current = '', depth = 0) {
1596
- const length = params.trim().length;
1597
- // biome-ignore lint/correctness/noUnreachable: recursive
1598
- for (let i = 0; i < length; i++) {
1599
- const char = params[i];
1600
- const tail = params.slice(i + 1);
1601
- switch (char) {
1602
- case ',':
1603
- return depth === 0
1604
- ? splitParameters(tail, [...result, current.trim()])
1605
- : splitParameters(tail, result, `${current}${char}`, depth);
1606
- case '(':
1607
- return splitParameters(tail, result, `${current}${char}`, depth + 1);
1608
- case ')':
1609
- return splitParameters(tail, result, `${current}${char}`, depth - 1);
1610
- default:
1611
- return splitParameters(tail, result, `${current}${char}`, depth);
1612
- }
1613
- }
1614
- if (current === '')
1615
- return result;
1616
- if (depth !== 0)
1617
- throw new InvalidParenthesisError({ current, depth });
1618
- result.push(current.trim());
1619
- return result;
1620
- }
1621
- function isSolidityType(type) {
1622
- return (type === 'address' ||
1623
- type === 'bool' ||
1624
- type === 'function' ||
1625
- type === 'string' ||
1626
- bytesRegex.test(type) ||
1627
- integerRegex$1.test(type));
1628
- }
1629
- const protectedKeywordsRegex = /^(?:after|alias|anonymous|apply|auto|byte|calldata|case|catch|constant|copyof|default|defined|error|event|external|false|final|function|immutable|implements|in|indexed|inline|internal|let|mapping|match|memory|mutable|null|of|override|partial|private|promise|public|pure|reference|relocatable|return|returns|sizeof|static|storage|struct|super|supports|switch|this|true|try|typedef|typeof|var|view|virtual)$/;
1630
- /** @internal */
1631
- function isSolidityKeyword(name) {
1632
- return (name === 'address' ||
1633
- name === 'bool' ||
1634
- name === 'function' ||
1635
- name === 'string' ||
1636
- name === 'tuple' ||
1637
- bytesRegex.test(name) ||
1638
- integerRegex$1.test(name) ||
1639
- protectedKeywordsRegex.test(name));
1640
- }
1641
- /** @internal */
1642
- function isValidDataLocation(type, isArray) {
1643
- return isArray || type === 'bytes' || type === 'string' || type === 'tuple';
1644
- }
1645
-
1646
- function parseStructs(signatures) {
1647
- // Create "shallow" version of each struct (and filter out non-structs or invalid structs)
1648
- const shallowStructs = {};
1649
- const signaturesLength = signatures.length;
1650
- for (let i = 0; i < signaturesLength; i++) {
1651
- const signature = signatures[i];
1652
- if (!isStructSignature(signature))
1653
- continue;
1654
- const match = execStructSignature(signature);
1655
- if (!match)
1656
- throw new InvalidSignatureError({ signature, type: 'struct' });
1657
- const properties = match.properties.split(';');
1658
- const components = [];
1659
- const propertiesLength = properties.length;
1660
- for (let k = 0; k < propertiesLength; k++) {
1661
- const property = properties[k];
1662
- const trimmed = property.trim();
1663
- if (!trimmed)
1664
- continue;
1665
- const abiParameter = parseAbiParameter(trimmed, {
1666
- type: 'struct',
1667
- });
1668
- components.push(abiParameter);
1669
- }
1670
- if (!components.length)
1671
- throw new InvalidStructSignatureError({ signature });
1672
- shallowStructs[match.name] = components;
1673
- }
1674
- // Resolve nested structs inside each parameter
1675
- const resolvedStructs = {};
1676
- const entries = Object.entries(shallowStructs);
1677
- const entriesLength = entries.length;
1678
- for (let i = 0; i < entriesLength; i++) {
1679
- const [name, parameters] = entries[i];
1680
- resolvedStructs[name] = resolveStructs(parameters, shallowStructs);
1681
- }
1682
- return resolvedStructs;
1683
- }
1684
- const typeWithoutTupleRegex = /^(?<type>[a-zA-Z$_][a-zA-Z0-9$_]*)(?<array>(?:\[\d*?\])+?)?$/;
1685
- function resolveStructs(abiParameters = [], structs = {}, ancestors = new Set()) {
1686
- const components = [];
1687
- const length = abiParameters.length;
1688
- for (let i = 0; i < length; i++) {
1689
- const abiParameter = abiParameters[i];
1690
- const isTuple = isTupleRegex.test(abiParameter.type);
1691
- if (isTuple)
1692
- components.push(abiParameter);
1693
- else {
1694
- const match = execTyped(typeWithoutTupleRegex, abiParameter.type);
1695
- if (!match?.type)
1696
- throw new InvalidAbiTypeParameterError({ abiParameter });
1697
- const { array, type } = match;
1698
- if (type in structs) {
1699
- if (ancestors.has(type))
1700
- throw new CircularReferenceError({ type });
1701
- components.push({
1702
- ...abiParameter,
1703
- type: `tuple${array ?? ''}`,
1704
- components: resolveStructs(structs[type], structs, new Set([...ancestors, type])),
1705
- });
1706
- }
1707
- else {
1708
- if (isSolidityType(type))
1709
- components.push(abiParameter);
1710
- else
1711
- throw new UnknownTypeError({ type });
1712
- }
1713
- }
1714
- }
1715
- return components;
1716
- }
1717
-
1718
- /**
1719
- * Parses human-readable ABI into JSON {@link Abi}
1720
- *
1721
- * @param signatures - Human-Readable ABI
1722
- * @returns Parsed {@link Abi}
1723
- *
1724
- * @example
1725
- * const abi = parseAbi([
1726
- * // ^? const abi: readonly [{ name: "balanceOf"; type: "function"; stateMutability:...
1727
- * 'function balanceOf(address owner) view returns (uint256)',
1728
- * 'event Transfer(address indexed from, address indexed to, uint256 amount)',
1729
- * ])
1730
- */
1731
- function parseAbi(signatures) {
1732
- const structs = parseStructs(signatures);
1733
- const abi = [];
1734
- const length = signatures.length;
1735
- for (let i = 0; i < length; i++) {
1736
- const signature = signatures[i];
1737
- if (isStructSignature(signature))
1738
- continue;
1739
- abi.push(parseSignature(signature, structs));
1740
- }
1741
- return abi;
1742
- }
1743
-
1744
- function formatAbiItem(abiItem, { includeName = false } = {}) {
1745
- if (abiItem.type !== 'function' &&
1746
- abiItem.type !== 'event' &&
1747
- abiItem.type !== 'error')
1748
- throw new InvalidDefinitionTypeError(abiItem.type);
1749
- return `${abiItem.name}(${formatAbiParams(abiItem.inputs, { includeName })})`;
1750
- }
1751
- function formatAbiParams(params, { includeName = false } = {}) {
1752
- if (!params)
1753
- return '';
1754
- return params
1755
- .map((param) => formatAbiParam(param, { includeName }))
1756
- .join(includeName ? ', ' : ',');
1757
- }
1758
- function formatAbiParam(param, { includeName }) {
1759
- if (param.type.startsWith('tuple')) {
1760
- return `(${formatAbiParams(param.components, { includeName })})${param.type.slice('tuple'.length)}`;
1761
- }
1762
- return param.type + (includeName && param.name ? ` ${param.name}` : '');
1763
- }
1764
-
1765
- function isHex(value, { strict = true } = {}) {
1766
- if (!value)
1767
- return false;
1768
- if (typeof value !== 'string')
1769
- return false;
1770
- return strict ? /^0x[0-9a-fA-F]*$/.test(value) : value.startsWith('0x');
1771
- }
1772
-
1773
- /**
1774
- * @description Retrieves the size of the value (in bytes).
1775
- *
1776
- * @param value The value (hex or byte array) to retrieve the size of.
1777
- * @returns The size of the value (in bytes).
1778
- */
1779
- function size(value) {
1780
- if (isHex(value, { strict: false }))
1781
- return Math.ceil((value.length - 2) / 2);
1782
- return value.length;
1783
- }
1784
-
1785
- const version = '2.47.10';
1786
-
1787
- let errorConfig = {
1788
- getDocsUrl: ({ docsBaseUrl, docsPath = '', docsSlug, }) => docsPath
1789
- ? `${docsBaseUrl ?? 'https://viem.sh'}${docsPath}${docsSlug ? `#${docsSlug}` : ''}`
1790
- : undefined,
1791
- version: `viem@${version}`,
1792
- };
1793
- class BaseError extends Error {
1794
- constructor(shortMessage, args = {}) {
1795
- const details = (() => {
1796
- if (args.cause instanceof BaseError)
1797
- return args.cause.details;
1798
- if (args.cause?.message)
1799
- return args.cause.message;
1800
- return args.details;
1801
- })();
1802
- const docsPath = (() => {
1803
- if (args.cause instanceof BaseError)
1804
- return args.cause.docsPath || args.docsPath;
1805
- return args.docsPath;
1806
- })();
1807
- const docsUrl = errorConfig.getDocsUrl?.({ ...args, docsPath });
1808
- const message = [
1809
- shortMessage || 'An error occurred.',
1810
- '',
1811
- ...(args.metaMessages ? [...args.metaMessages, ''] : []),
1812
- ...(docsUrl ? [`Docs: ${docsUrl}`] : []),
1813
- ...(details ? [`Details: ${details}`] : []),
1814
- ...(errorConfig.version ? [`Version: ${errorConfig.version}`] : []),
1815
- ].join('\n');
1816
- super(message, args.cause ? { cause: args.cause } : undefined);
1817
- Object.defineProperty(this, "details", {
1818
- enumerable: true,
1819
- configurable: true,
1820
- writable: true,
1821
- value: void 0
1822
- });
1823
- Object.defineProperty(this, "docsPath", {
1824
- enumerable: true,
1825
- configurable: true,
1826
- writable: true,
1827
- value: void 0
1828
- });
1829
- Object.defineProperty(this, "metaMessages", {
1830
- enumerable: true,
1831
- configurable: true,
1832
- writable: true,
1833
- value: void 0
1834
- });
1835
- Object.defineProperty(this, "shortMessage", {
1836
- enumerable: true,
1837
- configurable: true,
1838
- writable: true,
1839
- value: void 0
1840
- });
1841
- Object.defineProperty(this, "version", {
1842
- enumerable: true,
1843
- configurable: true,
1844
- writable: true,
1845
- value: void 0
1846
- });
1847
- Object.defineProperty(this, "name", {
1848
- enumerable: true,
1849
- configurable: true,
1850
- writable: true,
1851
- value: 'BaseError'
1852
- });
1853
- this.details = details;
1854
- this.docsPath = docsPath;
1855
- this.metaMessages = args.metaMessages;
1856
- this.name = args.name ?? this.name;
1857
- this.shortMessage = shortMessage;
1858
- this.version = version;
1859
- }
1860
- walk(fn) {
1861
- return walk(this, fn);
1862
- }
1863
- }
1864
- function walk(err, fn) {
1865
- if (fn?.(err))
1866
- return err;
1867
- if (err &&
1868
- typeof err === 'object' &&
1869
- 'cause' in err &&
1870
- err.cause !== undefined)
1871
- return walk(err.cause, fn);
1872
- return fn ? null : err;
1873
- }
1874
-
1875
- class AbiEncodingArrayLengthMismatchError extends BaseError {
1876
- constructor({ expectedLength, givenLength, type, }) {
1877
- super([
1878
- `ABI encoding array length mismatch for type ${type}.`,
1879
- `Expected length: ${expectedLength}`,
1880
- `Given length: ${givenLength}`,
1881
- ].join('\n'), { name: 'AbiEncodingArrayLengthMismatchError' });
1882
- }
1883
- }
1884
- class AbiEncodingBytesSizeMismatchError extends BaseError {
1885
- constructor({ expectedSize, value }) {
1886
- super(`Size of bytes "${value}" (bytes${size(value)}) does not match expected size (bytes${expectedSize}).`, { name: 'AbiEncodingBytesSizeMismatchError' });
1887
- }
1888
- }
1889
- class AbiEncodingLengthMismatchError extends BaseError {
1890
- constructor({ expectedLength, givenLength, }) {
1891
- super([
1892
- 'ABI encoding params/values length mismatch.',
1893
- `Expected length (params): ${expectedLength}`,
1894
- `Given length (values): ${givenLength}`,
1895
- ].join('\n'), { name: 'AbiEncodingLengthMismatchError' });
1896
- }
1897
- }
1898
- class AbiFunctionNotFoundError extends BaseError {
1899
- constructor(functionName, { docsPath } = {}) {
1900
- super([
1901
- `Function ${functionName ? `"${functionName}" ` : ''}not found on ABI.`,
1902
- 'Make sure you are using the correct ABI and that the function exists on it.',
1903
- ].join('\n'), {
1904
- docsPath,
1905
- name: 'AbiFunctionNotFoundError',
1906
- });
1907
- }
1908
- }
1909
- class AbiItemAmbiguityError extends BaseError {
1910
- constructor(x, y) {
1911
- super('Found ambiguous types in overloaded ABI items.', {
1912
- metaMessages: [
1913
- `\`${x.type}\` in \`${formatAbiItem(x.abiItem)}\`, and`,
1914
- `\`${y.type}\` in \`${formatAbiItem(y.abiItem)}\``,
1915
- '',
1916
- 'These types encode differently and cannot be distinguished at runtime.',
1917
- 'Remove one of the ambiguous items in the ABI.',
1918
- ],
1919
- name: 'AbiItemAmbiguityError',
1920
- });
1921
- }
1922
- }
1923
- class InvalidAbiEncodingTypeError extends BaseError {
1924
- constructor(type, { docsPath }) {
1925
- super([
1926
- `Type "${type}" is not a valid encoding type.`,
1927
- 'Please provide a valid ABI type.',
1928
- ].join('\n'), { docsPath, name: 'InvalidAbiEncodingType' });
1929
- }
1930
- }
1931
- class InvalidArrayError extends BaseError {
1932
- constructor(value) {
1933
- super([`Value "${value}" is not a valid array.`].join('\n'), {
1934
- name: 'InvalidArrayError',
1935
- });
1936
- }
1937
- }
1938
- class InvalidDefinitionTypeError extends BaseError {
1939
- constructor(type) {
1940
- super([
1941
- `"${type}" is not a valid definition type.`,
1942
- 'Valid types: "function", "event", "error"',
1943
- ].join('\n'), { name: 'InvalidDefinitionTypeError' });
1944
- }
1945
- }
1946
-
1947
- class SliceOffsetOutOfBoundsError extends BaseError {
1948
- constructor({ offset, position, size, }) {
1949
- super(`Slice ${position === 'start' ? 'starting' : 'ending'} at offset "${offset}" is out-of-bounds (size: ${size}).`, { name: 'SliceOffsetOutOfBoundsError' });
1950
- }
1951
- }
1952
- class SizeExceedsPaddingSizeError extends BaseError {
1953
- constructor({ size, targetSize, type, }) {
1954
- super(`${type.charAt(0).toUpperCase()}${type
1955
- .slice(1)
1956
- .toLowerCase()} size (${size}) exceeds padding size (${targetSize}).`, { name: 'SizeExceedsPaddingSizeError' });
1957
- }
1958
- }
1959
-
1960
- function pad(hexOrBytes, { dir, size = 32 } = {}) {
1961
- if (typeof hexOrBytes === 'string')
1962
- return padHex(hexOrBytes, { dir, size });
1963
- return padBytes(hexOrBytes, { dir, size });
1964
- }
1965
- function padHex(hex_, { dir, size = 32 } = {}) {
1966
- if (size === null)
1967
- return hex_;
1968
- const hex = hex_.replace('0x', '');
1969
- if (hex.length > size * 2)
1970
- throw new SizeExceedsPaddingSizeError({
1971
- size: Math.ceil(hex.length / 2),
1972
- targetSize: size,
1973
- type: 'hex',
1974
- });
1975
- return `0x${hex[dir === 'right' ? 'padEnd' : 'padStart'](size * 2, '0')}`;
1976
- }
1977
- function padBytes(bytes, { dir, size = 32 } = {}) {
1978
- if (size === null)
1979
- return bytes;
1980
- if (bytes.length > size)
1981
- throw new SizeExceedsPaddingSizeError({
1982
- size: bytes.length,
1983
- targetSize: size,
1984
- type: 'bytes',
1985
- });
1986
- const paddedBytes = new Uint8Array(size);
1987
- for (let i = 0; i < size; i++) {
1988
- const padEnd = dir === 'right';
1989
- paddedBytes[padEnd ? i : size - i - 1] =
1990
- bytes[padEnd ? i : bytes.length - i - 1];
1991
- }
1992
- return paddedBytes;
1993
- }
1994
-
1995
- class IntegerOutOfRangeError extends BaseError {
1996
- constructor({ max, min, signed, size, value, }) {
1997
- super(`Number "${value}" is not in safe ${size ? `${size * 8}-bit ${signed ? 'signed' : 'unsigned'} ` : ''}integer range ${max ? `(${min} to ${max})` : `(above ${min})`}`, { name: 'IntegerOutOfRangeError' });
1998
- }
1999
- }
2000
- class SizeOverflowError extends BaseError {
2001
- constructor({ givenSize, maxSize }) {
2002
- super(`Size cannot exceed ${maxSize} bytes. Given size: ${givenSize} bytes.`, { name: 'SizeOverflowError' });
2003
- }
2004
- }
2005
-
2006
- function assertSize(hexOrBytes, { size: size$1 }) {
2007
- if (size(hexOrBytes) > size$1)
2008
- throw new SizeOverflowError({
2009
- givenSize: size(hexOrBytes),
2010
- maxSize: size$1,
2011
- });
2012
- }
2013
-
2014
- const hexes = /*#__PURE__*/ Array.from({ length: 256 }, (_v, i) => i.toString(16).padStart(2, '0'));
2015
- /**
2016
- * Encodes a string, number, bigint, or ByteArray into a hex string
2017
- *
2018
- * - Docs: https://viem.sh/docs/utilities/toHex
2019
- * - Example: https://viem.sh/docs/utilities/toHex#usage
2020
- *
2021
- * @param value Value to encode.
2022
- * @param opts Options.
2023
- * @returns Hex value.
2024
- *
2025
- * @example
2026
- * import { toHex } from 'viem'
2027
- * const data = toHex('Hello world')
2028
- * // '0x48656c6c6f20776f726c6421'
2029
- *
2030
- * @example
2031
- * import { toHex } from 'viem'
2032
- * const data = toHex(420)
2033
- * // '0x1a4'
2034
- *
2035
- * @example
2036
- * import { toHex } from 'viem'
2037
- * const data = toHex('Hello world', { size: 32 })
2038
- * // '0x48656c6c6f20776f726c64210000000000000000000000000000000000000000'
2039
- */
2040
- function toHex(value, opts = {}) {
2041
- if (typeof value === 'number' || typeof value === 'bigint')
2042
- return numberToHex(value, opts);
2043
- if (typeof value === 'string') {
2044
- return stringToHex(value, opts);
2045
- }
2046
- if (typeof value === 'boolean')
2047
- return boolToHex(value, opts);
2048
- return bytesToHex(value, opts);
2049
- }
2050
- /**
2051
- * Encodes a boolean into a hex string
2052
- *
2053
- * - Docs: https://viem.sh/docs/utilities/toHex#booltohex
2054
- *
2055
- * @param value Value to encode.
2056
- * @param opts Options.
2057
- * @returns Hex value.
2058
- *
2059
- * @example
2060
- * import { boolToHex } from 'viem'
2061
- * const data = boolToHex(true)
2062
- * // '0x1'
2063
- *
2064
- * @example
2065
- * import { boolToHex } from 'viem'
2066
- * const data = boolToHex(false)
2067
- * // '0x0'
2068
- *
2069
- * @example
2070
- * import { boolToHex } from 'viem'
2071
- * const data = boolToHex(true, { size: 32 })
2072
- * // '0x0000000000000000000000000000000000000000000000000000000000000001'
2073
- */
2074
- function boolToHex(value, opts = {}) {
2075
- const hex = `0x${Number(value)}`;
2076
- if (typeof opts.size === 'number') {
2077
- assertSize(hex, { size: opts.size });
2078
- return pad(hex, { size: opts.size });
2079
- }
2080
- return hex;
2081
- }
2082
- /**
2083
- * Encodes a bytes array into a hex string
2084
- *
2085
- * - Docs: https://viem.sh/docs/utilities/toHex#bytestohex
2086
- *
2087
- * @param value Value to encode.
2088
- * @param opts Options.
2089
- * @returns Hex value.
2090
- *
2091
- * @example
2092
- * import { bytesToHex } from 'viem'
2093
- * const data = bytesToHex(Uint8Array.from([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33])
2094
- * // '0x48656c6c6f20576f726c6421'
2095
- *
2096
- * @example
2097
- * import { bytesToHex } from 'viem'
2098
- * const data = bytesToHex(Uint8Array.from([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]), { size: 32 })
2099
- * // '0x48656c6c6f20576f726c64210000000000000000000000000000000000000000'
2100
- */
2101
- function bytesToHex(value, opts = {}) {
2102
- let string = '';
2103
- for (let i = 0; i < value.length; i++) {
2104
- string += hexes[value[i]];
2105
- }
2106
- const hex = `0x${string}`;
2107
- if (typeof opts.size === 'number') {
2108
- assertSize(hex, { size: opts.size });
2109
- return pad(hex, { dir: 'right', size: opts.size });
2110
- }
2111
- return hex;
2112
- }
2113
- /**
2114
- * Encodes a number or bigint into a hex string
2115
- *
2116
- * - Docs: https://viem.sh/docs/utilities/toHex#numbertohex
2117
- *
2118
- * @param value Value to encode.
2119
- * @param opts Options.
2120
- * @returns Hex value.
2121
- *
2122
- * @example
2123
- * import { numberToHex } from 'viem'
2124
- * const data = numberToHex(420)
2125
- * // '0x1a4'
2126
- *
2127
- * @example
2128
- * import { numberToHex } from 'viem'
2129
- * const data = numberToHex(420, { size: 32 })
2130
- * // '0x00000000000000000000000000000000000000000000000000000000000001a4'
2131
- */
2132
- function numberToHex(value_, opts = {}) {
2133
- const { signed, size } = opts;
2134
- const value = BigInt(value_);
2135
- let maxValue;
2136
- if (size) {
2137
- if (signed)
2138
- maxValue = (1n << (BigInt(size) * 8n - 1n)) - 1n;
2139
- else
2140
- maxValue = 2n ** (BigInt(size) * 8n) - 1n;
2141
- }
2142
- else if (typeof value_ === 'number') {
2143
- maxValue = BigInt(Number.MAX_SAFE_INTEGER);
2144
- }
2145
- const minValue = typeof maxValue === 'bigint' && signed ? -maxValue - 1n : 0;
2146
- if ((maxValue && value > maxValue) || value < minValue) {
2147
- const suffix = typeof value_ === 'bigint' ? 'n' : '';
2148
- throw new IntegerOutOfRangeError({
2149
- max: maxValue ? `${maxValue}${suffix}` : undefined,
2150
- min: `${minValue}${suffix}`,
2151
- signed,
2152
- size,
2153
- value: `${value_}${suffix}`,
2154
- });
2155
- }
2156
- const hex = `0x${(signed && value < 0 ? (1n << BigInt(size * 8)) + BigInt(value) : value).toString(16)}`;
2157
- if (size)
2158
- return pad(hex, { size });
2159
- return hex;
2160
- }
2161
- const encoder$1 = /*#__PURE__*/ new TextEncoder();
2162
- /**
2163
- * Encodes a UTF-8 string into a hex string
2164
- *
2165
- * - Docs: https://viem.sh/docs/utilities/toHex#stringtohex
2166
- *
2167
- * @param value Value to encode.
2168
- * @param opts Options.
2169
- * @returns Hex value.
2170
- *
2171
- * @example
2172
- * import { stringToHex } from 'viem'
2173
- * const data = stringToHex('Hello World!')
2174
- * // '0x48656c6c6f20576f726c6421'
2175
- *
2176
- * @example
2177
- * import { stringToHex } from 'viem'
2178
- * const data = stringToHex('Hello World!', { size: 32 })
2179
- * // '0x48656c6c6f20576f726c64210000000000000000000000000000000000000000'
2180
- */
2181
- function stringToHex(value_, opts = {}) {
2182
- const value = encoder$1.encode(value_);
2183
- return bytesToHex(value, opts);
2184
- }
2185
-
2186
- const encoder = /*#__PURE__*/ new TextEncoder();
2187
- /**
2188
- * Encodes a UTF-8 string, hex value, bigint, number or boolean to a byte array.
2189
- *
2190
- * - Docs: https://viem.sh/docs/utilities/toBytes
2191
- * - Example: https://viem.sh/docs/utilities/toBytes#usage
2192
- *
2193
- * @param value Value to encode.
2194
- * @param opts Options.
2195
- * @returns Byte array value.
2196
- *
2197
- * @example
2198
- * import { toBytes } from 'viem'
2199
- * const data = toBytes('Hello world')
2200
- * // Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33])
2201
- *
2202
- * @example
2203
- * import { toBytes } from 'viem'
2204
- * const data = toBytes(420)
2205
- * // Uint8Array([1, 164])
2206
- *
2207
- * @example
2208
- * import { toBytes } from 'viem'
2209
- * const data = toBytes(420, { size: 4 })
2210
- * // Uint8Array([0, 0, 1, 164])
2211
- */
2212
- function toBytes$1(value, opts = {}) {
2213
- if (typeof value === 'number' || typeof value === 'bigint')
2214
- return numberToBytes(value, opts);
2215
- if (typeof value === 'boolean')
2216
- return boolToBytes(value, opts);
2217
- if (isHex(value))
2218
- return hexToBytes(value, opts);
2219
- return stringToBytes(value, opts);
2220
- }
2221
- /**
2222
- * Encodes a boolean into a byte array.
2223
- *
2224
- * - Docs: https://viem.sh/docs/utilities/toBytes#booltobytes
2225
- *
2226
- * @param value Boolean value to encode.
2227
- * @param opts Options.
2228
- * @returns Byte array value.
2229
- *
2230
- * @example
2231
- * import { boolToBytes } from 'viem'
2232
- * const data = boolToBytes(true)
2233
- * // Uint8Array([1])
2234
- *
2235
- * @example
2236
- * import { boolToBytes } from 'viem'
2237
- * const data = boolToBytes(true, { size: 32 })
2238
- * // Uint8Array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1])
2239
- */
2240
- function boolToBytes(value, opts = {}) {
2241
- const bytes = new Uint8Array(1);
2242
- bytes[0] = Number(value);
2243
- if (typeof opts.size === 'number') {
2244
- assertSize(bytes, { size: opts.size });
2245
- return pad(bytes, { size: opts.size });
2246
- }
2247
- return bytes;
2248
- }
2249
- // We use very optimized technique to convert hex string to byte array
2250
- const charCodeMap = {
2251
- zero: 48,
2252
- nine: 57,
2253
- A: 65,
2254
- F: 70,
2255
- a: 97,
2256
- f: 102,
2257
- };
2258
- function charCodeToBase16(char) {
2259
- if (char >= charCodeMap.zero && char <= charCodeMap.nine)
2260
- return char - charCodeMap.zero;
2261
- if (char >= charCodeMap.A && char <= charCodeMap.F)
2262
- return char - (charCodeMap.A - 10);
2263
- if (char >= charCodeMap.a && char <= charCodeMap.f)
2264
- return char - (charCodeMap.a - 10);
2265
- return undefined;
2266
- }
2267
- /**
2268
- * Encodes a hex string into a byte array.
2269
- *
2270
- * - Docs: https://viem.sh/docs/utilities/toBytes#hextobytes
2271
- *
2272
- * @param hex Hex string to encode.
2273
- * @param opts Options.
2274
- * @returns Byte array value.
2275
- *
2276
- * @example
2277
- * import { hexToBytes } from 'viem'
2278
- * const data = hexToBytes('0x48656c6c6f20776f726c6421')
2279
- * // Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33])
2280
- *
2281
- * @example
2282
- * import { hexToBytes } from 'viem'
2283
- * const data = hexToBytes('0x48656c6c6f20776f726c6421', { size: 32 })
2284
- * // Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
2285
- */
2286
- function hexToBytes(hex_, opts = {}) {
2287
- let hex = hex_;
2288
- if (opts.size) {
2289
- assertSize(hex, { size: opts.size });
2290
- hex = pad(hex, { dir: 'right', size: opts.size });
2291
- }
2292
- let hexString = hex.slice(2);
2293
- if (hexString.length % 2)
2294
- hexString = `0${hexString}`;
2295
- const length = hexString.length / 2;
2296
- const bytes = new Uint8Array(length);
2297
- for (let index = 0, j = 0; index < length; index++) {
2298
- const nibbleLeft = charCodeToBase16(hexString.charCodeAt(j++));
2299
- const nibbleRight = charCodeToBase16(hexString.charCodeAt(j++));
2300
- if (nibbleLeft === undefined || nibbleRight === undefined) {
2301
- throw new BaseError(`Invalid byte sequence ("${hexString[j - 2]}${hexString[j - 1]}" in "${hexString}").`);
2302
- }
2303
- bytes[index] = nibbleLeft * 16 + nibbleRight;
2304
- }
2305
- return bytes;
2306
- }
2307
- /**
2308
- * Encodes a number into a byte array.
2309
- *
2310
- * - Docs: https://viem.sh/docs/utilities/toBytes#numbertobytes
2311
- *
2312
- * @param value Number to encode.
2313
- * @param opts Options.
2314
- * @returns Byte array value.
2315
- *
2316
- * @example
2317
- * import { numberToBytes } from 'viem'
2318
- * const data = numberToBytes(420)
2319
- * // Uint8Array([1, 164])
2320
- *
2321
- * @example
2322
- * import { numberToBytes } from 'viem'
2323
- * const data = numberToBytes(420, { size: 4 })
2324
- * // Uint8Array([0, 0, 1, 164])
2325
- */
2326
- function numberToBytes(value, opts) {
2327
- const hex = numberToHex(value, opts);
2328
- return hexToBytes(hex);
2329
- }
2330
- /**
2331
- * Encodes a UTF-8 string into a byte array.
2332
- *
2333
- * - Docs: https://viem.sh/docs/utilities/toBytes#stringtobytes
2334
- *
2335
- * @param value String to encode.
2336
- * @param opts Options.
2337
- * @returns Byte array value.
2338
- *
2339
- * @example
2340
- * import { stringToBytes } from 'viem'
2341
- * const data = stringToBytes('Hello world!')
2342
- * // Uint8Array([72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 33])
2343
- *
2344
- * @example
2345
- * import { stringToBytes } from 'viem'
2346
- * const data = stringToBytes('Hello world!', { size: 32 })
2347
- * // Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
2348
- */
2349
- function stringToBytes(value, opts = {}) {
2350
- const bytes = encoder.encode(value);
2351
- if (typeof opts.size === 'number') {
2352
- assertSize(bytes, { size: opts.size });
2353
- return pad(bytes, { dir: 'right', size: opts.size });
2354
- }
2355
- return bytes;
2356
- }
2357
-
2358
- /**
2359
- * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.
2360
- * @todo re-check https://issues.chromium.org/issues/42212588
2361
- * @module
2362
- */
2363
- const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
2364
- const _32n = /* @__PURE__ */ BigInt(32);
2365
- function fromBig(n, le = false) {
2366
- if (le)
2367
- return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };
2368
- return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
2369
- }
2370
- function split(lst, le = false) {
2371
- const len = lst.length;
2372
- let Ah = new Uint32Array(len);
2373
- let Al = new Uint32Array(len);
2374
- for (let i = 0; i < len; i++) {
2375
- const { h, l } = fromBig(lst[i], le);
2376
- [Ah[i], Al[i]] = [h, l];
2377
- }
2378
- return [Ah, Al];
2379
- }
2380
- // Left rotate for Shift in [1, 32)
2381
- const rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));
2382
- const rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));
2383
- // Left rotate for Shift in (32, 64), NOTE: 32 is special case.
2384
- const rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));
2385
- const rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));
2386
-
2387
- /**
2388
- * Utilities for hex, bytes, CSPRNG.
2389
- * @module
2390
- */
2391
- /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
2392
- // We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.
2393
- // node.js versions earlier than v19 don't declare it in global scope.
2394
- // For node.js, package.json#exports field mapping rewrites import
2395
- // from `crypto` to `cryptoNode`, which imports native module.
2396
- // Makes the utils un-importable in browsers without a bundler.
2397
- // Once node.js 18 is deprecated (2025-04-30), we can just drop the import.
2398
- /** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */
2399
- function isBytes(a) {
2400
- return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');
2401
- }
2402
- /** Asserts something is positive integer. */
2403
- function anumber(n) {
2404
- if (!Number.isSafeInteger(n) || n < 0)
2405
- throw new Error('positive integer expected, got ' + n);
2406
- }
2407
- /** Asserts something is Uint8Array. */
2408
- function abytes(b, ...lengths) {
2409
- if (!isBytes(b))
2410
- throw new Error('Uint8Array expected');
2411
- if (lengths.length > 0 && !lengths.includes(b.length))
2412
- throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);
2413
- }
2414
- /** Asserts a hash instance has not been destroyed / finished */
2415
- function aexists(instance, checkFinished = true) {
2416
- if (instance.destroyed)
2417
- throw new Error('Hash instance has been destroyed');
2418
- if (checkFinished && instance.finished)
2419
- throw new Error('Hash#digest() has already been called');
2420
- }
2421
- /** Asserts output is properly-sized byte array */
2422
- function aoutput(out, instance) {
2423
- abytes(out);
2424
- const min = instance.outputLen;
2425
- if (out.length < min) {
2426
- throw new Error('digestInto() expects output buffer of length at least ' + min);
2427
- }
2428
- }
2429
- /** Cast u8 / u16 / u32 to u32. */
2430
- function u32(arr) {
2431
- return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
2432
- }
2433
- /** Zeroize a byte array. Warning: JS provides no guarantees. */
2434
- function clean(...arrays) {
2435
- for (let i = 0; i < arrays.length; i++) {
2436
- arrays[i].fill(0);
2437
- }
2438
- }
2439
- /** Is current platform little-endian? Most are. Big-Endian platform: IBM */
2440
- const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();
2441
- /** The byte swap operation for uint32 */
2442
- function byteSwap(word) {
2443
- return (((word << 24) & 0xff000000) |
2444
- ((word << 8) & 0xff0000) |
2445
- ((word >>> 8) & 0xff00) |
2446
- ((word >>> 24) & 0xff));
2447
- }
2448
- /** In place byte swap for Uint32Array */
2449
- function byteSwap32(arr) {
2450
- for (let i = 0; i < arr.length; i++) {
2451
- arr[i] = byteSwap(arr[i]);
2452
- }
2453
- return arr;
2454
- }
2455
- const swap32IfBE = isLE
2456
- ? (u) => u
2457
- : byteSwap32;
2458
- /**
2459
- * Converts string to bytes using UTF8 encoding.
2460
- * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])
2461
- */
2462
- function utf8ToBytes(str) {
2463
- if (typeof str !== 'string')
2464
- throw new Error('string expected');
2465
- return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
2466
- }
2467
- /**
2468
- * Normalizes (non-hex) string or Uint8Array to Uint8Array.
2469
- * Warning: when Uint8Array is passed, it would NOT get copied.
2470
- * Keep in mind for future mutable operations.
2471
- */
2472
- function toBytes(data) {
2473
- if (typeof data === 'string')
2474
- data = utf8ToBytes(data);
2475
- abytes(data);
2476
- return data;
2477
- }
2478
- /** For runtime check if class implements interface */
2479
- class Hash {
2480
- }
2481
- /** Wraps hash function, creating an interface on top of it */
2482
- function createHasher(hashCons) {
2483
- const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
2484
- const tmp = hashCons();
2485
- hashC.outputLen = tmp.outputLen;
2486
- hashC.blockLen = tmp.blockLen;
2487
- hashC.create = () => hashCons();
2488
- return hashC;
2489
- }
2490
-
2491
- /**
2492
- * SHA3 (keccak) hash function, based on a new "Sponge function" design.
2493
- * Different from older hashes, the internal state is bigger than output size.
2494
- *
2495
- * Check out [FIPS-202](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf),
2496
- * [Website](https://keccak.team/keccak.html),
2497
- * [the differences between SHA-3 and Keccak](https://crypto.stackexchange.com/questions/15727/what-are-the-key-differences-between-the-draft-sha-3-standard-and-the-keccak-sub).
2498
- *
2499
- * Check out `sha3-addons` module for cSHAKE, k12, and others.
2500
- * @module
2501
- */
2502
- // No __PURE__ annotations in sha3 header:
2503
- // EVERYTHING is in fact used on every export.
2504
- // Various per round constants calculations
2505
- const _0n = BigInt(0);
2506
- const _1n = BigInt(1);
2507
- const _2n = BigInt(2);
2508
- const _7n = BigInt(7);
2509
- const _256n = BigInt(256);
2510
- const _0x71n = BigInt(0x71);
2511
- const SHA3_PI = [];
2512
- const SHA3_ROTL = [];
2513
- const _SHA3_IOTA = [];
2514
- for (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {
2515
- // Pi
2516
- [x, y] = [y, (2 * x + 3 * y) % 5];
2517
- SHA3_PI.push(2 * (5 * y + x));
2518
- // Rotational
2519
- SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64);
2520
- // Iota
2521
- let t = _0n;
2522
- for (let j = 0; j < 7; j++) {
2523
- R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n;
2524
- if (R & _2n)
2525
- t ^= _1n << ((_1n << /* @__PURE__ */ BigInt(j)) - _1n);
2526
- }
2527
- _SHA3_IOTA.push(t);
2528
- }
2529
- const IOTAS = split(_SHA3_IOTA, true);
2530
- const SHA3_IOTA_H = IOTAS[0];
2531
- const SHA3_IOTA_L = IOTAS[1];
2532
- // Left rotation (without 0, 32, 64)
2533
- const rotlH = (h, l, s) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s));
2534
- const rotlL = (h, l, s) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s));
2535
- /** `keccakf1600` internal function, additionally allows to adjust round count. */
2536
- function keccakP(s, rounds = 24) {
2537
- const B = new Uint32Array(5 * 2);
2538
- // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js)
2539
- for (let round = 24 - rounds; round < 24; round++) {
2540
- // Theta θ
2541
- for (let x = 0; x < 10; x++)
2542
- B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];
2543
- for (let x = 0; x < 10; x += 2) {
2544
- const idx1 = (x + 8) % 10;
2545
- const idx0 = (x + 2) % 10;
2546
- const B0 = B[idx0];
2547
- const B1 = B[idx0 + 1];
2548
- const Th = rotlH(B0, B1, 1) ^ B[idx1];
2549
- const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];
2550
- for (let y = 0; y < 50; y += 10) {
2551
- s[x + y] ^= Th;
2552
- s[x + y + 1] ^= Tl;
2553
- }
2554
- }
2555
- // Rho (ρ) and Pi (π)
2556
- let curH = s[2];
2557
- let curL = s[3];
2558
- for (let t = 0; t < 24; t++) {
2559
- const shift = SHA3_ROTL[t];
2560
- const Th = rotlH(curH, curL, shift);
2561
- const Tl = rotlL(curH, curL, shift);
2562
- const PI = SHA3_PI[t];
2563
- curH = s[PI];
2564
- curL = s[PI + 1];
2565
- s[PI] = Th;
2566
- s[PI + 1] = Tl;
2567
- }
2568
- // Chi (χ)
2569
- for (let y = 0; y < 50; y += 10) {
2570
- for (let x = 0; x < 10; x++)
2571
- B[x] = s[y + x];
2572
- for (let x = 0; x < 10; x++)
2573
- s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];
2574
- }
2575
- // Iota (ι)
2576
- s[0] ^= SHA3_IOTA_H[round];
2577
- s[1] ^= SHA3_IOTA_L[round];
2578
- }
2579
- clean(B);
2580
- }
2581
- /** Keccak sponge function. */
2582
- class Keccak extends Hash {
2583
- // NOTE: we accept arguments in bytes instead of bits here.
2584
- constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {
2585
- super();
2586
- this.pos = 0;
2587
- this.posOut = 0;
2588
- this.finished = false;
2589
- this.destroyed = false;
2590
- this.enableXOF = false;
2591
- this.blockLen = blockLen;
2592
- this.suffix = suffix;
2593
- this.outputLen = outputLen;
2594
- this.enableXOF = enableXOF;
2595
- this.rounds = rounds;
2596
- // Can be passed from user as dkLen
2597
- anumber(outputLen);
2598
- // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes
2599
- // 0 < blockLen < 200
2600
- if (!(0 < blockLen && blockLen < 200))
2601
- throw new Error('only keccak-f1600 function is supported');
2602
- this.state = new Uint8Array(200);
2603
- this.state32 = u32(this.state);
2604
- }
2605
- clone() {
2606
- return this._cloneInto();
2607
- }
2608
- keccak() {
2609
- swap32IfBE(this.state32);
2610
- keccakP(this.state32, this.rounds);
2611
- swap32IfBE(this.state32);
2612
- this.posOut = 0;
2613
- this.pos = 0;
2614
- }
2615
- update(data) {
2616
- aexists(this);
2617
- data = toBytes(data);
2618
- abytes(data);
2619
- const { blockLen, state } = this;
2620
- const len = data.length;
2621
- for (let pos = 0; pos < len;) {
2622
- const take = Math.min(blockLen - this.pos, len - pos);
2623
- for (let i = 0; i < take; i++)
2624
- state[this.pos++] ^= data[pos++];
2625
- if (this.pos === blockLen)
2626
- this.keccak();
2627
- }
2628
- return this;
2629
- }
2630
- finish() {
2631
- if (this.finished)
2632
- return;
2633
- this.finished = true;
2634
- const { state, suffix, pos, blockLen } = this;
2635
- // Do the padding
2636
- state[pos] ^= suffix;
2637
- if ((suffix & 0x80) !== 0 && pos === blockLen - 1)
2638
- this.keccak();
2639
- state[blockLen - 1] ^= 0x80;
2640
- this.keccak();
2641
- }
2642
- writeInto(out) {
2643
- aexists(this, false);
2644
- abytes(out);
2645
- this.finish();
2646
- const bufferOut = this.state;
2647
- const { blockLen } = this;
2648
- for (let pos = 0, len = out.length; pos < len;) {
2649
- if (this.posOut >= blockLen)
2650
- this.keccak();
2651
- const take = Math.min(blockLen - this.posOut, len - pos);
2652
- out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);
2653
- this.posOut += take;
2654
- pos += take;
2655
- }
2656
- return out;
2657
- }
2658
- xofInto(out) {
2659
- // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF
2660
- if (!this.enableXOF)
2661
- throw new Error('XOF is not possible for this instance');
2662
- return this.writeInto(out);
2663
- }
2664
- xof(bytes) {
2665
- anumber(bytes);
2666
- return this.xofInto(new Uint8Array(bytes));
2667
- }
2668
- digestInto(out) {
2669
- aoutput(out, this);
2670
- if (this.finished)
2671
- throw new Error('digest() was already called');
2672
- this.writeInto(out);
2673
- this.destroy();
2674
- return out;
2675
- }
2676
- digest() {
2677
- return this.digestInto(new Uint8Array(this.outputLen));
2678
- }
2679
- destroy() {
2680
- this.destroyed = true;
2681
- clean(this.state);
2682
- }
2683
- _cloneInto(to) {
2684
- const { blockLen, suffix, outputLen, rounds, enableXOF } = this;
2685
- to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds));
2686
- to.state32.set(this.state32);
2687
- to.pos = this.pos;
2688
- to.posOut = this.posOut;
2689
- to.finished = this.finished;
2690
- to.rounds = rounds;
2691
- // Suffix can change in cSHAKE
2692
- to.suffix = suffix;
2693
- to.outputLen = outputLen;
2694
- to.enableXOF = enableXOF;
2695
- to.destroyed = this.destroyed;
2696
- return to;
2697
- }
2698
- }
2699
- const gen = (suffix, blockLen, outputLen) => createHasher(() => new Keccak(blockLen, suffix, outputLen));
2700
- /** keccak-256 hash function. Different from SHA3-256. */
2701
- const keccak_256 = /* @__PURE__ */ (() => gen(0x01, 136, 256 / 8))();
2702
-
2703
- function keccak256(value, to_) {
2704
- const to = to_ || 'hex';
2705
- const bytes = keccak_256(isHex(value, { strict: false }) ? toBytes$1(value) : value);
2706
- if (to === 'bytes')
2707
- return bytes;
2708
- return toHex(bytes);
2709
- }
2710
-
2711
- const hash = (value) => keccak256(toBytes$1(value));
2712
- function hashSignature(sig) {
2713
- return hash(sig);
2714
- }
2715
-
2716
- function normalizeSignature(signature) {
2717
- let active = true;
2718
- let current = '';
2719
- let level = 0;
2720
- let result = '';
2721
- let valid = false;
2722
- for (let i = 0; i < signature.length; i++) {
2723
- const char = signature[i];
2724
- // If the character is a separator, we want to reactivate.
2725
- if (['(', ')', ','].includes(char))
2726
- active = true;
2727
- // If the character is a "level" token, we want to increment/decrement.
2728
- if (char === '(')
2729
- level++;
2730
- if (char === ')')
2731
- level--;
2732
- // If we aren't active, we don't want to mutate the result.
2733
- if (!active)
2734
- continue;
2735
- // If level === 0, we are at the definition level.
2736
- if (level === 0) {
2737
- if (char === ' ' && ['event', 'function', ''].includes(result))
2738
- result = '';
2739
- else {
2740
- result += char;
2741
- // If we are at the end of the definition, we must be finished.
2742
- if (char === ')') {
2743
- valid = true;
2744
- break;
2745
- }
2746
- }
2747
- continue;
2748
- }
2749
- // Ignore spaces
2750
- if (char === ' ') {
2751
- // If the previous character is a separator, and the current section isn't empty, we want to deactivate.
2752
- if (signature[i - 1] !== ',' && current !== ',' && current !== ',(') {
2753
- current = '';
2754
- active = false;
2755
- }
2756
- continue;
2757
- }
2758
- result += char;
2759
- current += char;
2760
- }
2761
- if (!valid)
2762
- throw new BaseError('Unable to normalize signature.');
2763
- return result;
2764
- }
2765
-
2766
- /**
2767
- * Returns the signature for a given function or event definition.
2768
- *
2769
- * @example
2770
- * const signature = toSignature('function ownerOf(uint256 tokenId)')
2771
- * // 'ownerOf(uint256)'
2772
- *
2773
- * @example
2774
- * const signature_3 = toSignature({
2775
- * name: 'ownerOf',
2776
- * type: 'function',
2777
- * inputs: [{ name: 'tokenId', type: 'uint256' }],
2778
- * outputs: [],
2779
- * stateMutability: 'view',
2780
- * })
2781
- * // 'ownerOf(uint256)'
2782
- */
2783
- const toSignature = (def) => {
2784
- const def_ = (() => {
2785
- if (typeof def === 'string')
2786
- return def;
2787
- return formatAbiItem$1(def);
2788
- })();
2789
- return normalizeSignature(def_);
2790
- };
2791
-
2792
- /**
2793
- * Returns the hash (of the function/event signature) for a given event or function definition.
2794
- */
2795
- function toSignatureHash(fn) {
2796
- return hashSignature(toSignature(fn));
2797
- }
2798
-
2799
- /**
2800
- * Returns the event selector for a given event definition.
2801
- *
2802
- * @example
2803
- * const selector = toEventSelector('Transfer(address indexed from, address indexed to, uint256 amount)')
2804
- * // 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef
2805
- */
2806
- const toEventSelector = toSignatureHash;
2807
-
2808
- class InvalidAddressError extends BaseError {
2809
- constructor({ address }) {
2810
- super(`Address "${address}" is invalid.`, {
2811
- metaMessages: [
2812
- '- Address must be a hex value of 20 bytes (40 hex characters).',
2813
- '- Address must match its checksum counterpart.',
2814
- ],
2815
- name: 'InvalidAddressError',
2816
- });
2817
- }
2818
- }
2819
-
2820
- /**
2821
- * Map with a LRU (Least recently used) policy.
2822
- *
2823
- * @link https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU
2824
- */
2825
- class LruMap extends Map {
2826
- constructor(size) {
2827
- super();
2828
- Object.defineProperty(this, "maxSize", {
2829
- enumerable: true,
2830
- configurable: true,
2831
- writable: true,
2832
- value: void 0
2833
- });
2834
- this.maxSize = size;
2835
- }
2836
- get(key) {
2837
- const value = super.get(key);
2838
- if (super.has(key)) {
2839
- super.delete(key);
2840
- super.set(key, value);
2841
- }
2842
- return value;
2843
- }
2844
- set(key, value) {
2845
- if (super.has(key))
2846
- super.delete(key);
2847
- super.set(key, value);
2848
- if (this.maxSize && this.size > this.maxSize) {
2849
- const firstKey = super.keys().next().value;
2850
- if (firstKey !== undefined)
2851
- super.delete(firstKey);
2852
- }
2853
- return this;
2854
- }
2855
- }
2856
-
2857
- const checksumAddressCache = /*#__PURE__*/ new LruMap(8192);
2858
- function checksumAddress(address_,
2859
- /**
2860
- * Warning: EIP-1191 checksum addresses are generally not backwards compatible with the
2861
- * wider Ethereum ecosystem, meaning it will break when validated against an application/tool
2862
- * that relies on EIP-55 checksum encoding (checksum without chainId).
2863
- *
2864
- * It is highly recommended to not use this feature unless you
2865
- * know what you are doing.
2866
- *
2867
- * See more: https://github.com/ethereum/EIPs/issues/1121
2868
- */
2869
- chainId) {
2870
- if (checksumAddressCache.has(`${address_}.${chainId}`))
2871
- return checksumAddressCache.get(`${address_}.${chainId}`);
2872
- const hexAddress = address_.substring(2).toLowerCase();
2873
- const hash = keccak256(stringToBytes(hexAddress), 'bytes');
2874
- const address = (hexAddress).split('');
2875
- for (let i = 0; i < 40; i += 2) {
2876
- if (hash[i >> 1] >> 4 >= 8 && address[i]) {
2877
- address[i] = address[i].toUpperCase();
2878
- }
2879
- if ((hash[i >> 1] & 0x0f) >= 8 && address[i + 1]) {
2880
- address[i + 1] = address[i + 1].toUpperCase();
2881
- }
2882
- }
2883
- const result = `0x${address.join('')}`;
2884
- checksumAddressCache.set(`${address_}.${chainId}`, result);
2885
- return result;
2886
- }
2887
-
2888
- const addressRegex = /^0x[a-fA-F0-9]{40}$/;
2889
- /** @internal */
2890
- const isAddressCache = /*#__PURE__*/ new LruMap(8192);
2891
- function isAddress(address, options) {
2892
- const { strict = true } = options ?? {};
2893
- const cacheKey = `${address}.${strict}`;
2894
- if (isAddressCache.has(cacheKey))
2895
- return isAddressCache.get(cacheKey);
2896
- const result = (() => {
2897
- if (!addressRegex.test(address))
2898
- return false;
2899
- if (address.toLowerCase() === address)
2900
- return true;
2901
- if (strict)
2902
- return checksumAddress(address) === address;
2903
- return true;
2904
- })();
2905
- isAddressCache.set(cacheKey, result);
2906
- return result;
2907
- }
2908
-
2909
- function concat(values) {
2910
- if (typeof values[0] === 'string')
2911
- return concatHex(values);
2912
- return concatBytes(values);
2913
- }
2914
- function concatBytes(values) {
2915
- let length = 0;
2916
- for (const arr of values) {
2917
- length += arr.length;
2918
- }
2919
- const result = new Uint8Array(length);
2920
- let offset = 0;
2921
- for (const arr of values) {
2922
- result.set(arr, offset);
2923
- offset += arr.length;
2924
- }
2925
- return result;
2926
- }
2927
- function concatHex(values) {
2928
- return `0x${values.reduce((acc, x) => acc + x.replace('0x', ''), '')}`;
2929
- }
2930
-
2931
- /**
2932
- * @description Returns a section of the hex or byte array given a start/end bytes offset.
2933
- *
2934
- * @param value The hex or byte array to slice.
2935
- * @param start The start offset (in bytes).
2936
- * @param end The end offset (in bytes).
2937
- */
2938
- function slice(value, start, end, { strict } = {}) {
2939
- if (isHex(value, { strict: false }))
2940
- return sliceHex(value, start, end, {
2941
- strict,
2942
- });
2943
- return sliceBytes(value, start, end, {
2944
- strict,
2945
- });
2946
- }
2947
- function assertStartOffset(value, start) {
2948
- if (typeof start === 'number' && start > 0 && start > size(value) - 1)
2949
- throw new SliceOffsetOutOfBoundsError({
2950
- offset: start,
2951
- position: 'start',
2952
- size: size(value),
2953
- });
2954
- }
2955
- function assertEndOffset(value, start, end) {
2956
- if (typeof start === 'number' &&
2957
- typeof end === 'number' &&
2958
- size(value) !== end - start) {
2959
- throw new SliceOffsetOutOfBoundsError({
2960
- offset: end,
2961
- position: 'end',
2962
- size: size(value),
2963
- });
2964
- }
2965
- }
2966
- /**
2967
- * @description Returns a section of the byte array given a start/end bytes offset.
2968
- *
2969
- * @param value The byte array to slice.
2970
- * @param start The start offset (in bytes).
2971
- * @param end The end offset (in bytes).
2972
- */
2973
- function sliceBytes(value_, start, end, { strict } = {}) {
2974
- assertStartOffset(value_, start);
2975
- const value = value_.slice(start, end);
2976
- if (strict)
2977
- assertEndOffset(value, start, end);
2978
- return value;
2979
- }
2980
- /**
2981
- * @description Returns a section of the hex value given a start/end bytes offset.
2982
- *
2983
- * @param value The hex value to slice.
2984
- * @param start The start offset (in bytes).
2985
- * @param end The end offset (in bytes).
2986
- */
2987
- function sliceHex(value_, start, end, { strict } = {}) {
2988
- assertStartOffset(value_, start);
2989
- const value = `0x${value_
2990
- .replace('0x', '')
2991
- .slice((start ?? 0) * 2, (end ?? value_.length) * 2)}`;
2992
- if (strict)
2993
- assertEndOffset(value, start, end);
2994
- return value;
2995
- }
2996
-
2997
- // `(u)int<M>`: (un)signed integer type of `M` bits, `0 < M <= 256`, `M % 8 == 0`
2998
- // https://regexr.com/6v8hp
2999
- const integerRegex = /^(u?int)(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/;
3000
-
3001
- /**
3002
- * @description Encodes a list of primitive values into an ABI-encoded hex value.
3003
- *
3004
- * - Docs: https://viem.sh/docs/abi/encodeAbiParameters#encodeabiparameters
3005
- *
3006
- * Generates ABI encoded data using the [ABI specification](https://docs.soliditylang.org/en/latest/abi-spec), given a set of ABI parameters (inputs/outputs) and their corresponding values.
3007
- *
3008
- * @param params - a set of ABI Parameters (params), that can be in the shape of the inputs or outputs attribute of an ABI Item.
3009
- * @param values - a set of values (values) that correspond to the given params.
3010
- * @example
3011
- * ```typescript
3012
- * import { encodeAbiParameters } from 'viem'
3013
- *
3014
- * const encodedData = encodeAbiParameters(
3015
- * [
3016
- * { name: 'x', type: 'string' },
3017
- * { name: 'y', type: 'uint' },
3018
- * { name: 'z', type: 'bool' }
3019
- * ],
3020
- * ['wagmi', 420n, true]
3021
- * )
3022
- * ```
3023
- *
3024
- * You can also pass in Human Readable parameters with the parseAbiParameters utility.
3025
- *
3026
- * @example
3027
- * ```typescript
3028
- * import { encodeAbiParameters, parseAbiParameters } from 'viem'
3029
- *
3030
- * const encodedData = encodeAbiParameters(
3031
- * parseAbiParameters('string x, uint y, bool z'),
3032
- * ['wagmi', 420n, true]
3033
- * )
3034
- * ```
3035
- */
3036
- function encodeAbiParameters(params, values) {
3037
- if (params.length !== values.length)
3038
- throw new AbiEncodingLengthMismatchError({
3039
- expectedLength: params.length,
3040
- givenLength: values.length,
3041
- });
3042
- // Prepare the parameters to determine dynamic types to encode.
3043
- const preparedParams = prepareParams({
3044
- params: params,
3045
- values: values,
3046
- });
3047
- const data = encodeParams(preparedParams);
3048
- if (data.length === 0)
3049
- return '0x';
3050
- return data;
3051
- }
3052
- function prepareParams({ params, values, }) {
3053
- const preparedParams = [];
3054
- for (let i = 0; i < params.length; i++) {
3055
- preparedParams.push(prepareParam({ param: params[i], value: values[i] }));
3056
- }
3057
- return preparedParams;
3058
- }
3059
- function prepareParam({ param, value, }) {
3060
- const arrayComponents = getArrayComponents(param.type);
3061
- if (arrayComponents) {
3062
- const [length, type] = arrayComponents;
3063
- return encodeArray(value, { length, param: { ...param, type } });
3064
- }
3065
- if (param.type === 'tuple') {
3066
- return encodeTuple(value, {
3067
- param: param,
3068
- });
3069
- }
3070
- if (param.type === 'address') {
3071
- return encodeAddress(value);
3072
- }
3073
- if (param.type === 'bool') {
3074
- return encodeBool(value);
3075
- }
3076
- if (param.type.startsWith('uint') || param.type.startsWith('int')) {
3077
- const signed = param.type.startsWith('int');
3078
- const [, , size = '256'] = integerRegex.exec(param.type) ?? [];
3079
- return encodeNumber(value, {
3080
- signed,
3081
- size: Number(size),
3082
- });
3083
- }
3084
- if (param.type.startsWith('bytes')) {
3085
- return encodeBytes(value, { param });
3086
- }
3087
- if (param.type === 'string') {
3088
- return encodeString(value);
3089
- }
3090
- throw new InvalidAbiEncodingTypeError(param.type, {
3091
- docsPath: '/docs/contract/encodeAbiParameters',
3092
- });
3093
- }
3094
- function encodeParams(preparedParams) {
3095
- // 1. Compute the size of the static part of the parameters.
3096
- let staticSize = 0;
3097
- for (let i = 0; i < preparedParams.length; i++) {
3098
- const { dynamic, encoded } = preparedParams[i];
3099
- if (dynamic)
3100
- staticSize += 32;
3101
- else
3102
- staticSize += size(encoded);
3103
- }
3104
- // 2. Split the parameters into static and dynamic parts.
3105
- const staticParams = [];
3106
- const dynamicParams = [];
3107
- let dynamicSize = 0;
3108
- for (let i = 0; i < preparedParams.length; i++) {
3109
- const { dynamic, encoded } = preparedParams[i];
3110
- if (dynamic) {
3111
- staticParams.push(numberToHex(staticSize + dynamicSize, { size: 32 }));
3112
- dynamicParams.push(encoded);
3113
- dynamicSize += size(encoded);
3114
- }
3115
- else {
3116
- staticParams.push(encoded);
3117
- }
3118
- }
3119
- // 3. Concatenate static and dynamic parts.
3120
- return concat([...staticParams, ...dynamicParams]);
3121
- }
3122
- function encodeAddress(value) {
3123
- if (!isAddress(value))
3124
- throw new InvalidAddressError({ address: value });
3125
- return { dynamic: false, encoded: padHex(value.toLowerCase()) };
3126
- }
3127
- function encodeArray(value, { length, param, }) {
3128
- const dynamic = length === null;
3129
- if (!Array.isArray(value))
3130
- throw new InvalidArrayError(value);
3131
- if (!dynamic && value.length !== length)
3132
- throw new AbiEncodingArrayLengthMismatchError({
3133
- expectedLength: length,
3134
- givenLength: value.length,
3135
- type: `${param.type}[${length}]`,
3136
- });
3137
- let dynamicChild = false;
3138
- const preparedParams = [];
3139
- for (let i = 0; i < value.length; i++) {
3140
- const preparedParam = prepareParam({ param, value: value[i] });
3141
- if (preparedParam.dynamic)
3142
- dynamicChild = true;
3143
- preparedParams.push(preparedParam);
3144
- }
3145
- if (dynamic || dynamicChild) {
3146
- const data = encodeParams(preparedParams);
3147
- if (dynamic) {
3148
- const length = numberToHex(preparedParams.length, { size: 32 });
3149
- return {
3150
- dynamic: true,
3151
- encoded: preparedParams.length > 0 ? concat([length, data]) : length,
3152
- };
3153
- }
3154
- if (dynamicChild)
3155
- return { dynamic: true, encoded: data };
3156
- }
3157
- return {
3158
- dynamic: false,
3159
- encoded: concat(preparedParams.map(({ encoded }) => encoded)),
3160
- };
3161
- }
3162
- function encodeBytes(value, { param }) {
3163
- const [, paramSize] = param.type.split('bytes');
3164
- const bytesSize = size(value);
3165
- if (!paramSize) {
3166
- let value_ = value;
3167
- // If the size is not divisible by 32 bytes, pad the end
3168
- // with empty bytes to the ceiling 32 bytes.
3169
- if (bytesSize % 32 !== 0)
3170
- value_ = padHex(value_, {
3171
- dir: 'right',
3172
- size: Math.ceil((value.length - 2) / 2 / 32) * 32,
3173
- });
3174
- return {
3175
- dynamic: true,
3176
- encoded: concat([padHex(numberToHex(bytesSize, { size: 32 })), value_]),
3177
- };
3178
- }
3179
- if (bytesSize !== Number.parseInt(paramSize, 10))
3180
- throw new AbiEncodingBytesSizeMismatchError({
3181
- expectedSize: Number.parseInt(paramSize, 10),
3182
- value,
3183
- });
3184
- return { dynamic: false, encoded: padHex(value, { dir: 'right' }) };
3185
- }
3186
- function encodeBool(value) {
3187
- if (typeof value !== 'boolean')
3188
- throw new BaseError(`Invalid boolean value: "${value}" (type: ${typeof value}). Expected: \`true\` or \`false\`.`);
3189
- return { dynamic: false, encoded: padHex(boolToHex(value)) };
3190
- }
3191
- function encodeNumber(value, { signed, size = 256 }) {
3192
- if (typeof size === 'number') {
3193
- const max = 2n ** (BigInt(size) - (signed ? 1n : 0n)) - 1n;
3194
- const min = signed ? -max - 1n : 0n;
3195
- if (value > max || value < min)
3196
- throw new IntegerOutOfRangeError({
3197
- max: max.toString(),
3198
- min: min.toString(),
3199
- signed,
3200
- size: size / 8,
3201
- value: value.toString(),
3202
- });
3203
- }
3204
- return {
3205
- dynamic: false,
3206
- encoded: numberToHex(value, {
3207
- size: 32,
3208
- signed,
3209
- }),
3210
- };
3211
- }
3212
- function encodeString(value) {
3213
- const hexValue = stringToHex(value);
3214
- const partsLength = Math.ceil(size(hexValue) / 32);
3215
- const parts = [];
3216
- for (let i = 0; i < partsLength; i++) {
3217
- parts.push(padHex(slice(hexValue, i * 32, (i + 1) * 32), {
3218
- dir: 'right',
3219
- }));
3220
- }
3221
- return {
3222
- dynamic: true,
3223
- encoded: concat([
3224
- padHex(numberToHex(size(hexValue), { size: 32 })),
3225
- ...parts,
3226
- ]),
3227
- };
3228
- }
3229
- function encodeTuple(value, { param }) {
3230
- let dynamic = false;
3231
- const preparedParams = [];
3232
- for (let i = 0; i < param.components.length; i++) {
3233
- const param_ = param.components[i];
3234
- const index = Array.isArray(value) ? i : param_.name;
3235
- const preparedParam = prepareParam({
3236
- param: param_,
3237
- value: value[index],
3238
- });
3239
- preparedParams.push(preparedParam);
3240
- if (preparedParam.dynamic)
3241
- dynamic = true;
3242
- }
3243
- return {
3244
- dynamic,
3245
- encoded: dynamic
3246
- ? encodeParams(preparedParams)
3247
- : concat(preparedParams.map(({ encoded }) => encoded)),
3248
- };
3249
- }
3250
- function getArrayComponents(type) {
3251
- const matches = type.match(/^(.*)\[(\d+)?\]$/);
3252
- return matches
3253
- ? // Return `null` if the array is dynamic.
3254
- [matches[2] ? Number(matches[2]) : null, matches[1]]
3255
- : undefined;
3256
- }
3257
-
3258
- /**
3259
- * Returns the function selector for a given function definition.
3260
- *
3261
- * @example
3262
- * const selector = toFunctionSelector('function ownerOf(uint256 tokenId)')
3263
- * // 0x6352211e
3264
- */
3265
- const toFunctionSelector = (fn) => slice(toSignatureHash(fn), 0, 4);
3266
-
3267
- function getAbiItem(parameters) {
3268
- const { abi, args = [], name } = parameters;
3269
- const isSelector = isHex(name, { strict: false });
3270
- const abiItems = abi.filter((abiItem) => {
3271
- if (isSelector) {
3272
- if (abiItem.type === 'function')
3273
- return toFunctionSelector(abiItem) === name;
3274
- if (abiItem.type === 'event')
3275
- return toEventSelector(abiItem) === name;
3276
- return false;
3277
- }
3278
- return 'name' in abiItem && abiItem.name === name;
3279
- });
3280
- if (abiItems.length === 0)
3281
- return undefined;
3282
- if (abiItems.length === 1)
3283
- return abiItems[0];
3284
- let matchedAbiItem;
3285
- for (const abiItem of abiItems) {
3286
- if (!('inputs' in abiItem))
3287
- continue;
3288
- if (!args || args.length === 0) {
3289
- if (!abiItem.inputs || abiItem.inputs.length === 0)
3290
- return abiItem;
3291
- continue;
3292
- }
3293
- if (!abiItem.inputs)
3294
- continue;
3295
- if (abiItem.inputs.length === 0)
3296
- continue;
3297
- if (abiItem.inputs.length !== args.length)
3298
- continue;
3299
- const matched = args.every((arg, index) => {
3300
- const abiParameter = 'inputs' in abiItem && abiItem.inputs[index];
3301
- if (!abiParameter)
3302
- return false;
3303
- return isArgOfType(arg, abiParameter);
3304
- });
3305
- if (matched) {
3306
- // Check for ambiguity against already matched parameters (e.g. `address` vs `bytes20`).
3307
- if (matchedAbiItem &&
3308
- 'inputs' in matchedAbiItem &&
3309
- matchedAbiItem.inputs) {
3310
- const ambiguousTypes = getAmbiguousTypes(abiItem.inputs, matchedAbiItem.inputs, args);
3311
- if (ambiguousTypes)
3312
- throw new AbiItemAmbiguityError({
3313
- abiItem,
3314
- type: ambiguousTypes[0],
3315
- }, {
3316
- abiItem: matchedAbiItem,
3317
- type: ambiguousTypes[1],
3318
- });
3319
- }
3320
- matchedAbiItem = abiItem;
3321
- }
3322
- }
3323
- if (matchedAbiItem)
3324
- return matchedAbiItem;
3325
- return abiItems[0];
3326
- }
3327
- /** @internal */
3328
- function isArgOfType(arg, abiParameter) {
3329
- const argType = typeof arg;
3330
- const abiParameterType = abiParameter.type;
3331
- switch (abiParameterType) {
3332
- case 'address':
3333
- return isAddress(arg, { strict: false });
3334
- case 'bool':
3335
- return argType === 'boolean';
3336
- case 'function':
3337
- return argType === 'string';
3338
- case 'string':
3339
- return argType === 'string';
3340
- default: {
3341
- if (abiParameterType === 'tuple' && 'components' in abiParameter)
3342
- return Object.values(abiParameter.components).every((component, index) => {
3343
- return (argType === 'object' &&
3344
- isArgOfType(Object.values(arg)[index], component));
3345
- });
3346
- // `(u)int<M>`: (un)signed integer type of `M` bits, `0 < M <= 256`, `M % 8 == 0`
3347
- // https://regexr.com/6v8hp
3348
- if (/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/.test(abiParameterType))
3349
- return argType === 'number' || argType === 'bigint';
3350
- // `bytes<M>`: binary type of `M` bytes, `0 < M <= 32`
3351
- // https://regexr.com/6va55
3352
- if (/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/.test(abiParameterType))
3353
- return argType === 'string' || arg instanceof Uint8Array;
3354
- // fixed-length (`<type>[M]`) and dynamic (`<type>[]`) arrays
3355
- // https://regexr.com/6va6i
3356
- if (/[a-z]+[1-9]{0,3}(\[[0-9]{0,}\])+$/.test(abiParameterType)) {
3357
- return (Array.isArray(arg) &&
3358
- arg.every((x) => isArgOfType(x, {
3359
- ...abiParameter,
3360
- // Pop off `[]` or `[M]` from end of type
3361
- type: abiParameterType.replace(/(\[[0-9]{0,}\])$/, ''),
3362
- })));
3363
- }
3364
- return false;
3365
- }
3366
- }
3367
- }
3368
- /** @internal */
3369
- function getAmbiguousTypes(sourceParameters, targetParameters, args) {
3370
- for (const parameterIndex in sourceParameters) {
3371
- const sourceParameter = sourceParameters[parameterIndex];
3372
- const targetParameter = targetParameters[parameterIndex];
3373
- if (sourceParameter.type === 'tuple' &&
3374
- targetParameter.type === 'tuple' &&
3375
- 'components' in sourceParameter &&
3376
- 'components' in targetParameter)
3377
- return getAmbiguousTypes(sourceParameter.components, targetParameter.components, args[parameterIndex]);
3378
- const types = [sourceParameter.type, targetParameter.type];
3379
- const ambiguous = (() => {
3380
- if (types.includes('address') && types.includes('bytes20'))
3381
- return true;
3382
- if (types.includes('address') && types.includes('string'))
3383
- return isAddress(args[parameterIndex], { strict: false });
3384
- if (types.includes('address') && types.includes('bytes'))
3385
- return isAddress(args[parameterIndex], { strict: false });
3386
- return false;
3387
- })();
3388
- if (ambiguous)
3389
- return types;
3390
- }
3391
- return;
3392
- }
3393
-
3394
- const docsPath = '/docs/contract/encodeFunctionData';
3395
- function prepareEncodeFunctionData(parameters) {
3396
- const { abi, args, functionName } = parameters;
3397
- let abiItem = abi[0];
3398
- if (functionName) {
3399
- const item = getAbiItem({
3400
- abi,
3401
- args,
3402
- name: functionName,
3403
- });
3404
- if (!item)
3405
- throw new AbiFunctionNotFoundError(functionName, { docsPath });
3406
- abiItem = item;
3407
- }
3408
- if (abiItem.type !== 'function')
3409
- throw new AbiFunctionNotFoundError(undefined, { docsPath });
3410
- return {
3411
- abi: [abiItem],
3412
- functionName: toFunctionSelector(formatAbiItem(abiItem)),
3413
- };
3414
- }
3415
-
3416
- function encodeFunctionData(parameters) {
3417
- const { args } = parameters;
3418
- const { abi, functionName } = (() => {
3419
- if (parameters.abi.length === 1 &&
3420
- parameters.functionName?.startsWith('0x'))
3421
- return parameters;
3422
- return prepareEncodeFunctionData(parameters);
3423
- })();
3424
- const abiItem = abi[0];
3425
- const signature = functionName;
3426
- const data = 'inputs' in abiItem && abiItem.inputs
3427
- ? encodeAbiParameters(abiItem.inputs, args ?? [])
3428
- : undefined;
3429
- return concatHex([signature, data ?? '0x']);
3430
- }
3431
-
3432
- const ZERO_ADDRESS$1 = "0x0000000000000000000000000000000000000000";
3433
- const PAYMENT_ABI = parseAbi([
3434
- "function createPayment(bytes32 paymentId, string vendorId, address token, uint256 amount, bytes backendSignature) external payable",
3435
- ]);
3436
- const ERC20_ABI = parseAbi([
3437
- "function allowance(address owner, address spender) view returns (uint256)",
3438
- "function approve(address spender, uint256 amount) returns (bool)",
3439
- ]);
3440
- function ensure0x(hex) {
3441
- return (hex.startsWith("0x") ? hex : `0x${hex}`);
3442
- }
3443
- class ContractService {
3444
- constructor(provider) {
3445
- this.provider = provider;
3446
- }
3447
- async getAddress() {
3448
- const accounts = (await this.provider.request({
3449
- method: "eth_requestAccounts",
3450
- }));
3451
- if (!accounts[0]) {
3452
- throw new KwesPayError("No wallet account available", "WALLET_REJECTED");
3453
- }
3454
- return accounts[0];
3455
- }
3456
- async waitForReceipt(txHash, timeoutMs = 120000) {
3457
- const deadline = Date.now() + timeoutMs;
3458
- while (Date.now() < deadline) {
3459
- const receipt = (await this.provider.request({
3460
- method: "eth_getTransactionReceipt",
3461
- params: [txHash],
3462
- }));
3463
- if (receipt) {
3464
- return {
3465
- blockNumber: parseInt(receipt.blockNumber, 16),
3466
- status: parseInt(receipt.status, 16),
3467
- };
3468
- }
3469
- await new Promise((r) => setTimeout(r, 2000));
3470
- }
3471
- throw new KwesPayError("Transaction receipt timeout — check wallet or block explorer", "CONTRACT_ERROR");
3472
- }
3473
- async ensureApproval(tokenAddress, amountBaseUnits, contractAddress, chainId, onStatus) {
3474
- if (tokenAddress === ZERO_ADDRESS$1)
3475
- return;
3476
- onStatus?.("Checking approval", "Verifying token allowance…");
3477
- const owner = await this.getAddress();
3478
- const amount = BigInt(amountBaseUnits);
3479
- const allowanceData = encodeFunctionData({
3480
- abi: ERC20_ABI,
3481
- functionName: "allowance",
3482
- args: [owner, ensure0x(contractAddress)],
3483
- });
3484
- const rawAllowance = (await this.provider.request({
3485
- method: "eth_call",
3486
- params: [{ to: ensure0x(tokenAddress), data: allowanceData }, "latest"],
3487
- }));
3488
- const allowance = rawAllowance && rawAllowance !== "0x" ? BigInt(rawAllowance) : 0n;
3489
- if (allowance >= amount)
3490
- return;
3491
- onStatus?.("Approve token", "Please approve in your wallet");
3492
- const approveData = encodeFunctionData({
3493
- abi: ERC20_ABI,
3494
- functionName: "approve",
3495
- args: [ensure0x(contractAddress), amount * 2n],
3496
- });
3497
- let txHash;
3498
- try {
3499
- txHash = (await this.provider.request({
3500
- method: "eth_sendTransaction",
3501
- params: [
3502
- { from: owner, to: ensure0x(tokenAddress), data: approveData },
3503
- ],
3504
- }));
3505
- }
3506
- catch (err) {
3507
- const msg = err instanceof Error ? err.message : String(err);
3508
- if (msg.includes("rejected") ||
3509
- msg.includes("denied") ||
3510
- msg.includes("ACTION_REJECTED")) {
3511
- throw new KwesPayError("Token approval cancelled by user", "APPROVAL_REJECTED", err);
3512
- }
3513
- throw new KwesPayError(`Token approval failed: ${msg}`, "CONTRACT_ERROR", err);
3514
- }
3515
- onStatus?.("Waiting for approval", `Tx: ${txHash.slice(0, 10)}…`);
3516
- const receipt = await this.waitForReceipt(txHash);
3517
- if (receipt.status !== 1) {
3518
- throw new KwesPayError("Approval transaction reverted", "CONTRACT_ERROR");
3519
- }
3520
- await new Promise((r) => setTimeout(r, 1000));
3521
- }
3522
- async createPayment(params, onStatus) {
3523
- const from = await this.getAddress();
3524
- const amount = BigInt(params.amountBaseUnits);
3525
- const isNative = params.tokenAddress === ZERO_ADDRESS$1;
3526
- const data = encodeFunctionData({
3527
- abi: PAYMENT_ABI,
3528
- functionName: "createPayment",
3529
- args: [
3530
- ensure0x(params.paymentIdBytes32),
3531
- params.vendorIdentifier,
3532
- ensure0x(params.tokenAddress),
3533
- amount,
3534
- ensure0x(params.backendSignature),
3535
- ],
3536
- });
3537
- onStatus?.("Confirm payment", "Please approve in your wallet");
3538
- const txParams = {
3539
- from,
3540
- to: ensure0x(params.contractAddress),
3541
- data,
3542
- };
3543
- if (isNative)
3544
- txParams["value"] = `0x${amount.toString(16)}`;
3545
- let txHash;
3546
- try {
3547
- txHash = (await this.provider.request({
3548
- method: "eth_sendTransaction",
3549
- params: [txParams],
3550
- }));
3551
- }
3552
- catch (err) {
3553
- const msg = err instanceof Error ? err.message : String(err);
3554
- if (msg.includes("rejected") ||
3555
- msg.includes("denied") ||
3556
- msg.includes("ACTION_REJECTED") ||
3557
- msg.includes("User denied")) {
3558
- throw new KwesPayError("Transaction cancelled by user", "WALLET_REJECTED", err);
3559
- }
3560
- throw new KwesPayError(`Contract call failed: ${msg}`, "CONTRACT_ERROR", err);
3561
- }
3562
- onStatus?.("Waiting for confirmation", `Tx: ${txHash.slice(0, 10)}…`);
3563
- const receipt = await this.waitForReceipt(txHash);
3564
- if (receipt.status !== 1) {
3565
- throw new KwesPayError("Payment transaction reverted", "CONTRACT_ERROR");
3566
- }
3567
- return { txHash, blockNumber: receipt.blockNumber };
3568
- }
3569
- }
3570
-
3571
- const ZERO_ADDRESS = "0x0000000000000000000000000000000000000000";
3572
- const GAS_BUFFER = 300000n * 2000000000n;
3573
- let PaymentService$1 = class PaymentService {
3574
- constructor(provider) {
3575
- this.provider = provider;
3576
- this.contractService = new ContractService(provider);
3577
- }
3578
- async ensureCorrectNetwork(expectedChainId, expectedNetwork, onStatus) {
3579
- const raw = (await this.provider.request({
3580
- method: "eth_chainId",
3581
- }));
3582
- const current = parseInt(raw, 16);
3583
- if (current === expectedChainId)
3584
- return;
3585
- onStatus?.("Switching network", `Switching to ${expectedNetwork} (chain ${expectedChainId})…`);
3586
- try {
3587
- await this.provider.request({
3588
- method: "wallet_switchEthereumChain",
3589
- params: [{ chainId: "0x" + expectedChainId.toString(16) }],
3590
- });
3591
- }
3592
- catch (switchErr) {
3593
- const errAny = switchErr;
3594
- if (errAny?.code === 4902) {
3595
- throw new KwesPayError(`Network ${expectedNetwork} (chain ${expectedChainId}) is not added to your wallet. Please add it manually and retry.`, "WRONG_NETWORK");
3596
- }
3597
- const msg = errAny?.message ?? String(switchErr);
3598
- if (msg.includes("rejected") ||
3599
- msg.includes("denied") ||
3600
- msg.includes("ACTION_REJECTED")) {
3601
- throw new KwesPayError(`Network switch to ${expectedNetwork} was rejected. Please switch manually and retry.`, "WRONG_NETWORK");
3602
- }
3603
- throw new KwesPayError(`Failed to switch to ${expectedNetwork}: ${msg}`, "WRONG_NETWORK");
3604
- }
3605
- const confirmedRaw = (await this.provider.request({
3606
- method: "eth_chainId",
3607
- }));
3608
- const confirmed = parseInt(confirmedRaw, 16);
3609
- if (confirmed !== expectedChainId) {
3610
- throw new KwesPayError(`Wallet is on chain ${confirmed} but payment requires chain ${expectedChainId} (${expectedNetwork}). Please switch your network and retry.`, "WRONG_NETWORK");
3611
- }
3612
- }
3613
- async ensureSufficientBalance(walletAddress, tokenAddress, amountBaseUnits, onStatus) {
3614
- const amount = BigInt(amountBaseUnits);
3615
- const isNative = tokenAddress === ZERO_ADDRESS;
3616
- onStatus?.("Checking balance", "Verifying wallet balance…");
3617
- const nativeRaw = (await this.provider.request({
3618
- method: "eth_getBalance",
3619
- params: [walletAddress, "latest"],
3620
- }));
3621
- const nativeBalance = nativeRaw && nativeRaw !== "0x" ? BigInt(nativeRaw) : 0n;
3622
- if (isNative) {
3623
- const required = amount + GAS_BUFFER;
3624
- if (nativeBalance < required) {
3625
- throw new KwesPayError(`Insufficient native balance. Required ~${(Number(required) / 1e18).toFixed(8)} ETH (payment + gas), available: ${(Number(nativeBalance) / 1e18).toFixed(8)} ETH.`, "INSUFFICIENT_BALANCE");
3626
- }
3627
- return;
3628
- }
3629
- if (nativeBalance < GAS_BUFFER) {
3630
- throw new KwesPayError(`Insufficient gas balance. Need at least ${(Number(GAS_BUFFER) / 1e18).toFixed(8)} ETH for gas, available: ${(Number(nativeBalance) / 1e18).toFixed(8)} ETH.`, "INSUFFICIENT_BALANCE");
3631
- }
3632
- const balanceData = "0x70a08231" + walletAddress.slice(2).toLowerCase().padStart(64, "0");
3633
- const raw = (await this.provider.request({
3634
- method: "eth_call",
3635
- params: [{ to: tokenAddress, data: balanceData }, "latest"],
3636
- }));
3637
- const tokenBalance = raw && raw !== "0x" ? BigInt(raw) : 0n;
3638
- if (tokenBalance < amount) {
3639
- throw new KwesPayError(`Insufficient token balance. Required: ${amount.toString()}, available: ${tokenBalance.toString()} (base units).`, "INSUFFICIENT_BALANCE");
3640
- }
3641
- }
3642
- async pay(params) {
3643
- const { provider, payload, onStatus } = params;
3644
- if (!payload.paymentIdBytes32 || !payload.backendSignature) {
3645
- throw new KwesPayError("Invalid transaction payload — missing paymentIdBytes32 or backendSignature", "TRANSACTION_FAILED");
3646
- }
3647
- if (!payload.vendorIdentifier) {
3648
- throw new KwesPayError("Invalid transaction payload — missing vendorIdentifier", "TRANSACTION_FAILED");
3649
- }
3650
- await this.ensureCorrectNetwork(payload.chainId, payload.network, onStatus);
3651
- const accounts = (await this.provider.request({
3652
- method: "eth_requestAccounts",
3653
- }));
3654
- const walletAddress = accounts[0];
3655
- await this.ensureSufficientBalance(walletAddress, payload.tokenAddress, payload.amountBaseUnits, onStatus);
3656
- const contractAddress = resolveContractAddress(payload.network);
3657
- await this.contractService.ensureApproval(payload.tokenAddress, payload.amountBaseUnits, contractAddress, payload.chainId, onStatus);
3658
- const { txHash, blockNumber } = await this.contractService.createPayment({
3659
- paymentIdBytes32: payload.paymentIdBytes32,
3660
- vendorIdentifier: payload.vendorIdentifier,
3661
- tokenAddress: payload.tokenAddress,
3662
- amountBaseUnits: payload.amountBaseUnits,
3663
- backendSignature: payload.backendSignature,
3664
- contractAddress,
3665
- chainId: payload.chainId,
3666
- }, onStatus);
3667
- return {
3668
- txHash,
3669
- blockNumber,
3670
- transactionReference: payload.transactionReference,
3671
- paymentIdBytes32: payload.paymentIdBytes32,
3672
- };
3673
- }
3674
- };
3675
-
3676
- class KwesPayClient {
3677
- constructor(config) {
3678
- if (!config.apiKey)
3679
- throw new KwesPayError("apiKey is required", "INVALID_KEY");
3680
- this.apiKey = config.apiKey;
3681
- }
3682
- async validateKey() {
3683
- const data = await gqlRequest(GQL_VALIDATE_KEY, {
3684
- accessKey: this.apiKey,
3685
- });
3686
- const r = data.validateAccessKey;
3687
- if (!r.isValid) {
3688
- return {
3689
- isValid: false,
3690
- error: r.error ?? "Invalid access key",
3691
- };
3692
- }
3693
- return {
3694
- isValid: true,
3695
- keyId: r.keyId,
3696
- keyLabel: r.keyLabel,
3697
- activeFlag: r.activeFlag,
3698
- expirationDate: r.expirationDate,
3699
- vendorInfo: r.vendorInfo,
3700
- scope: {
3701
- allowedVendors: r.allowedVendors ?? null,
3702
- allowedNetworks: r.allowedNetworks ?? null,
3703
- allowedTokens: r.allowedTokens ?? null,
3704
- },
3705
- };
3706
- }
3707
- async getQuote(params) {
3708
- const data = await gqlRequest(GQL_CREATE_QUOTE, {
3709
- input: {
3710
- vendorIdentifier: params.vendorIdentifier,
3711
- fiatAmount: params.fiatAmount,
3712
- fiatCurrency: params.fiatCurrency ?? "USD",
3713
- cryptoCurrency: params.cryptoCurrency,
3714
- network: params.network,
3715
- },
3716
- }, this.apiKey);
3717
- const q = data.createQuote;
3718
- if (!q.success) {
3719
- const msg = q.message ?? "Quote creation failed";
3720
- const code = msg.toLowerCase().includes("expired")
3721
- ? "QUOTE_EXPIRED"
3722
- : msg.toLowerCase().includes("key")
3723
- ? "INVALID_KEY"
3724
- : "UNKNOWN";
3725
- throw new KwesPayError(msg, code);
3726
- }
3727
- return {
3728
- quoteId: q.quoteId,
3729
- cryptoCurrency: q.cryptoCurrency,
3730
- tokenAddress: q.tokenAddress,
3731
- amountBaseUnits: q.amountBaseUnits,
3732
- displayAmount: q.displayAmount,
3733
- network: q.network,
3734
- chainId: q.chainId,
3735
- expiresAt: q.expiresAt,
3736
- };
3737
- }
3738
- async quote(params) {
3739
- const quoteData = await gqlRequest(GQL_CREATE_QUOTE, {
3740
- input: {
3741
- vendorIdentifier: params.vendorIdentifier,
3742
- fiatAmount: params.fiatAmount,
3743
- fiatCurrency: params.fiatCurrency ?? "USD",
3744
- cryptoCurrency: params.cryptoCurrency,
3745
- network: params.network,
3746
- },
3747
- }, this.apiKey);
3748
- const q = quoteData.createQuote;
3749
- if (!q.success) {
3750
- const msg = q.message ?? "Quote creation failed";
3751
- const code = msg.toLowerCase().includes("expired")
3752
- ? "QUOTE_EXPIRED"
3753
- : msg.toLowerCase().includes("key")
3754
- ? "INVALID_KEY"
3755
- : "UNKNOWN";
3756
- throw new KwesPayError(msg, code);
3757
- }
3758
- const txData = await gqlRequest(GQL_CREATE_TRANSACTION, {
3759
- input: {
3760
- quoteId: q.quoteId,
3761
- payerWalletAddress: params.payerWalletAddress,
3762
- },
3763
- }, this.apiKey);
3764
- const t = txData.createTransaction;
3765
- if (!t.success) {
3766
- const msg = t.message ?? "Transaction creation failed";
3767
- const code = msg.toLowerCase().includes("expired")
3768
- ? "QUOTE_EXPIRED"
3769
- : msg.toLowerCase().includes("already been used")
3770
- ? "QUOTE_USED"
3771
- : msg.toLowerCase().includes("not found")
3772
- ? "QUOTE_NOT_FOUND"
3773
- : msg.toLowerCase().includes("key")
3774
- ? "INVALID_KEY"
3775
- : "UNKNOWN";
3776
- throw new KwesPayError(msg, code);
3777
- }
3778
- return {
3779
- paymentIdBytes32: t.paymentIdBytes32,
3780
- backendSignature: t.backendSignature,
3781
- tokenAddress: t.tokenAddress,
3782
- amountBaseUnits: t.amountBaseUnits,
3783
- chainId: t.chainId,
3784
- expiresAt: t.expiresAt,
3785
- transactionReference: t.transaction.transactionReference,
3786
- transactionStatus: t.transaction.transactionStatus,
3787
- network: params.network,
3788
- vendorIdentifier: params.vendorIdentifier,
3789
- };
3790
- }
3791
- async pay(params) {
3792
- return new PaymentService$1(params.provider).pay(params);
3793
- }
3794
- async getTransactionStatus(transactionReference) {
3795
- const data = await gqlRequest(GQL_TRANSACTION_STATUS, {
3796
- transactionReference,
3797
- });
3798
- const r = data.getTransactionStatus;
3799
- return {
3800
- transactionReference: r.transactionReference,
3801
- transactionStatus: r.transactionStatus,
3802
- blockchainHash: r.blockchainHash,
3803
- blockchainNetwork: r.blockchainNetwork,
3804
- displayAmount: r.displayAmount,
3805
- cryptoCurrency: r.cryptoCurrency,
3806
- payerWalletAddress: r.payerWalletAddress,
3807
- initiatedAt: r.initiatedAt,
3808
- };
3809
- }
3810
- async pollTransactionStatus(transactionReference, options = {}) {
3811
- const { onStatus, intervalMs = 4000, maxAttempts = 60 } = options;
3812
- let attempts = 0;
3813
- const terminal = [
3814
- "completed",
3815
- "failed",
3816
- "expired",
3817
- "underpaid",
3818
- "overpaid",
3819
- "refunded",
3820
- ];
3821
- return new Promise((resolve, reject) => {
3822
- const id = setInterval(async () => {
3823
- attempts++;
3824
- try {
3825
- const status = await this.getTransactionStatus(transactionReference);
3826
- onStatus?.(status.transactionStatus);
3827
- if (terminal.includes(status.transactionStatus)) {
3828
- clearInterval(id);
3829
- resolve(status);
3830
- }
3831
- else if (attempts >= maxAttempts) {
3832
- clearInterval(id);
3833
- reject(new KwesPayError("Status polling timed out", "UNKNOWN"));
3834
- }
3835
- }
3836
- catch (err) {
3837
- if (attempts >= maxAttempts) {
3838
- clearInterval(id);
3839
- reject(err);
3840
- }
3841
- }
3842
- }, intervalMs);
3843
- });
3844
- }
3845
- }
3846
-
3847
808
  class PaymentService {
3848
809
  constructor(apiKey, graphqlEndpoint) {
3849
810
  this.apiKey = apiKey;
@@ -3855,10 +816,13 @@ class PaymentService {
3855
816
  });
3856
817
  }
3857
818
 
3858
- _initClient() {
819
+ async _initClient() {
3859
820
  if (this.client) return;
3860
821
 
3861
822
  console.log("[KwesPay] Initializing SDK client...");
823
+
824
+ const { KwesPayClient } = await import('./index-338l55OY.js');
825
+
3862
826
  this.client = new KwesPayClient({ apiKey: this.apiKey });
3863
827
 
3864
828
  console.log("[KwesPay] SDK client ready");
@@ -3866,7 +830,7 @@ class PaymentService {
3866
830
 
3867
831
  async validateAPIKey() {
3868
832
  try {
3869
- this._initClient();
833
+ await this._initClient();
3870
834
 
3871
835
  const result = await this.client.validateKey();
3872
836
 
@@ -3890,7 +854,7 @@ class PaymentService {
3890
854
  }
3891
855
 
3892
856
  async getQuote(params) {
3893
- this._initClient();
857
+ await this._initClient();
3894
858
 
3895
859
  console.log("[KwesPay] Requesting quote...", params);
3896
860
 
@@ -3909,7 +873,7 @@ class PaymentService {
3909
873
  }
3910
874
 
3911
875
  async createPayment({ payload, walletProvider, onStatusUpdate }) {
3912
- this._initClient();
876
+ await this._initClient();
3913
877
 
3914
878
  console.log("[KwesPay] 💳 createPayment called", {
3915
879
  payloadKeys: payload ? Object.keys(payload) : null,
@@ -3970,7 +934,7 @@ class PaymentService {
3970
934
  }
3971
935
 
3972
936
  async getTransactionStatus(transactionReference) {
3973
- this._initClient();
937
+ await this._initClient();
3974
938
 
3975
939
  console.log("[KwesPay] Fetching transaction status:", transactionReference);
3976
940
 
@@ -3985,7 +949,7 @@ class PaymentService {
3985
949
  transactionReference,
3986
950
  { onStatus, intervalMs = 4000, maxAttempts = 60 } = {}
3987
951
  ) {
3988
- this._initClient();
952
+ await this._initClient();
3989
953
 
3990
954
  console.log("[KwesPay] Starting polling...", {
3991
955
  transactionReference,