@corpus-core/colibri-stateless 1.1.1 → 1.1.3
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.
- package/README.md +26 -0
- package/c4w.js +1 -1
- package/c4w.wasm +0 -0
- package/cjs/chains.js +84 -0
- package/cjs/connectionState.js +156 -0
- package/cjs/eventEmitter.js +54 -0
- package/cjs/http.js +172 -0
- package/cjs/index.js +327 -0
- package/cjs/package.json +3 -0
- package/cjs/strategy.js +114 -0
- package/cjs/subscriptionManager.js +314 -0
- package/cjs/transactionVerifier.js +202 -0
- package/cjs/types.js +71 -0
- package/cjs/wasm.js +65 -0
- package/cjs/wasm_cjs.js +65 -0
- package/cjs/wasm_shared.js +200 -0
- package/index.d.ts +1 -0
- package/index.js +2 -0
- package/package.json +9 -5
- package/wasm.d.ts +8 -52
- package/wasm.js +38 -152
- package/wasm_cjs.d.ts +30 -0
- package/wasm_cjs.js +58 -0
- package/wasm_shared.d.ts +68 -0
- package/wasm_shared.js +190 -0
package/README.md
CHANGED
|
@@ -14,6 +14,32 @@ The colibri client is a stateless and trustless ethereum client, which is optimi
|
|
|
14
14
|
npm install @corpus-core/colibri-stateless
|
|
15
15
|
```
|
|
16
16
|
|
|
17
|
+
## Import / Usage (ESM and CommonJS)
|
|
18
|
+
|
|
19
|
+
Colibri is published as a **dual package** and can be used in both ESM and CommonJS environments.
|
|
20
|
+
|
|
21
|
+
### ESM (browsers, modern bundlers, Node ESM)
|
|
22
|
+
|
|
23
|
+
```js
|
|
24
|
+
import Colibri, { Strategy, set_wasm_url } from "@corpus-core/colibri-stateless";
|
|
25
|
+
|
|
26
|
+
// Optional: only needed if you want to pin the WASM location explicitly
|
|
27
|
+
// set_wasm_url("https://example.com/c4w.wasm");
|
|
28
|
+
|
|
29
|
+
const client = new Colibri();
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
### CommonJS (e.g. Jest, older Node toolchains)
|
|
33
|
+
|
|
34
|
+
```js
|
|
35
|
+
const { default: Colibri, Strategy, set_wasm_url } = require("@corpus-core/colibri-stateless");
|
|
36
|
+
|
|
37
|
+
// Optional: in Node you can explicitly point to the wasm file path
|
|
38
|
+
// set_wasm_url(require("node:path").join(__dirname, "c4w.wasm"));
|
|
39
|
+
|
|
40
|
+
const client = new Colibri();
|
|
41
|
+
```
|
|
42
|
+
|
|
17
43
|
## Using Colibri as RPC Provider
|
|
18
44
|
|
|
19
45
|
The Colibri Class implements the EIP-1193 Interface, so any library supporting EIP-1193 Providers can easily use Colibri as RPCProvider.
|
package/c4w.js
CHANGED
|
@@ -5,7 +5,7 @@ var c4w = (() => {
|
|
|
5
5
|
async function(moduleArg = {}) {
|
|
6
6
|
var moduleRtn;
|
|
7
7
|
|
|
8
|
-
var Module=moduleArg;var readyPromiseResolve,readyPromiseReject;var readyPromise=new Promise((resolve,reject)=>{readyPromiseResolve=resolve;readyPromiseReject=reject});var ENVIRONMENT_IS_WEB=typeof window=="object";var ENVIRONMENT_IS_WORKER=typeof WorkerGlobalScope!="undefined";var ENVIRONMENT_IS_NODE=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string"&&process.type!="renderer";if(ENVIRONMENT_IS_NODE){const{createRequire}=await import("module");var require=createRequire(import.meta.url)}var moduleOverrides=Object.assign({},Module);var arguments_=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("fs");var nodePath=require("path");if(!import.meta.url.startsWith("data:")){scriptDirectory=nodePath.dirname(require("url").fileURLToPath(import.meta.url))+"/"}readBinary=filename=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename);return ret};readAsync=async(filename,binary=true)=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename,binary?undefined:"utf8");return ret};if(!Module["thisProgram"]&&process.argv.length>1){thisProgram=process.argv[1].replace(/\\/g,"/")}arguments_=process.argv.slice(2);quit_=(status,toThrow)=>{process.exitCode=status;throw toThrow}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){if(ENVIRONMENT_IS_WORKER){scriptDirectory=self.location.href}else if(typeof document!="undefined"&&document.currentScript){scriptDirectory=document.currentScript.src}if(_scriptName){scriptDirectory=_scriptName}if(scriptDirectory.startsWith("blob:")){scriptDirectory=""}else{scriptDirectory=scriptDirectory.slice(0,scriptDirectory.replace(/[?#].*/,"").lastIndexOf("/")+1)}{readAsync=async url=>{var response=await fetch(url,{credentials:"same-origin"});if(response.ok){return response.arrayBuffer()}throw new Error(response.status+" : "+response.url)}}}else{}var out=Module["print"]||console.log.bind(console);var err=Module["printErr"]||console.error.bind(console);Object.assign(Module,moduleOverrides);moduleOverrides=null;if(Module["arguments"])arguments_=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];var wasmBinary=Module["wasmBinary"];var wasmMemory;var ABORT=false;var EXITSTATUS;var HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAP64,HEAPU64,HEAPF64;var runtimeInitialized=false;var isFileURI=filename=>filename.startsWith("file://");function updateMemoryViews(){var b=wasmMemory.buffer;Module["HEAP8"]=HEAP8=new Int8Array(b);Module["HEAP16"]=HEAP16=new Int16Array(b);Module["HEAPU8"]=HEAPU8=new Uint8Array(b);Module["HEAPU16"]=HEAPU16=new Uint16Array(b);Module["HEAP32"]=HEAP32=new Int32Array(b);Module["HEAPU32"]=HEAPU32=new Uint32Array(b);Module["HEAPF32"]=HEAPF32=new Float32Array(b);Module["HEAPF64"]=HEAPF64=new Float64Array(b);Module["HEAP64"]=HEAP64=new BigInt64Array(b);Module["HEAPU64"]=HEAPU64=new BigUint64Array(b)}function preRun(){if(Module["preRun"]){if(typeof Module["preRun"]=="function")Module["preRun"]=[Module["preRun"]];while(Module["preRun"].length){addOnPreRun(Module["preRun"].shift())}}callRuntimeCallbacks(onPreRuns)}function initRuntime(){runtimeInitialized=true;wasmExports["r"]()}function postRun(){if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"].length){addOnPostRun(Module["postRun"].shift())}}callRuntimeCallbacks(onPostRuns)}var runDependencies=0;var dependenciesFulfilled=null;function addRunDependency(id){runDependencies++;Module["monitorRunDependencies"]?.(runDependencies)}function removeRunDependency(id){runDependencies--;Module["monitorRunDependencies"]?.(runDependencies);if(runDependencies==0){if(dependenciesFulfilled){var callback=dependenciesFulfilled;dependenciesFulfilled=null;callback()}}}function abort(what){Module["onAbort"]?.(what);what="Aborted("+what+")";err(what);ABORT=true;what+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(what);readyPromiseReject(e);throw e}var wasmBinaryFile;function findWasmBinary(){if(Module["locateFile"]){return locateFile("c4w.wasm")}return new URL("c4w.wasm",import.meta.url).href}function getBinarySync(file){if(file==wasmBinaryFile&&wasmBinary){return new Uint8Array(wasmBinary)}if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}async function getWasmBinary(binaryFile){if(!wasmBinary){try{var response=await readAsync(binaryFile);return new Uint8Array(response)}catch{}}return getBinarySync(binaryFile)}async function instantiateArrayBuffer(binaryFile,imports){try{var binary=await getWasmBinary(binaryFile);var instance=await WebAssembly.instantiate(binary,imports);return instance}catch(reason){err(`failed to asynchronously prepare wasm: ${reason}`);abort(reason)}}async function instantiateAsync(binary,binaryFile,imports){if(!binary&&typeof WebAssembly.instantiateStreaming=="function"&&!ENVIRONMENT_IS_NODE){try{var response=fetch(binaryFile,{credentials:"same-origin"});var instantiationResult=await WebAssembly.instantiateStreaming(response,imports);return instantiationResult}catch(reason){err(`wasm streaming compile failed: ${reason}`);err("falling back to ArrayBuffer instantiation")}}return instantiateArrayBuffer(binaryFile,imports)}function getWasmImports(){return{a:wasmImports}}async function createWasm(){function receiveInstance(instance,module){wasmExports=instance.exports;wasmMemory=wasmExports["q"];updateMemoryViews();removeRunDependency("wasm-instantiate");return wasmExports}addRunDependency("wasm-instantiate");function receiveInstantiationResult(result){return receiveInstance(result["instance"])}var info=getWasmImports();if(Module["instantiateWasm"]){return new Promise((resolve,reject)=>{Module["instantiateWasm"](info,(mod,inst)=>{receiveInstance(mod,inst);resolve(mod.exports)})})}wasmBinaryFile??=findWasmBinary();try{var result=await instantiateAsync(wasmBinary,wasmBinaryFile,info);var exports=receiveInstantiationResult(result);return exports}catch(e){readyPromiseReject(e);return Promise.reject(e)}}var ASM_CONSTS={164636:($0,$1)=>{var keyStr=UTF8ToString($0);var data=Module.storage.get(keyStr);if(data){var bufferPtr=_c4w_buffer_alloc($1,data.length);HEAPU8.set(data,bufferPtr);return 1}return 0},164824:($0,$1,$2)=>{var keyStr=UTF8ToString($0);var array=new Uint8Array($2);array.set(HEAPU8.subarray($1,$1+$2));Module.storage.set(keyStr,array)},164967:$0=>{var keyStr=UTF8ToString($0);Module.storage.del(keyStr)}};class ExitStatus{name="ExitStatus";constructor(status){this.message=`Program terminated with exit(${status})`;this.status=status}}var callRuntimeCallbacks=callbacks=>{while(callbacks.length>0){callbacks.shift()(Module)}};var onPostRuns=[];var addOnPostRun=cb=>onPostRuns.unshift(cb);var onPreRuns=[];var addOnPreRun=cb=>onPreRuns.unshift(cb);var noExitRuntime=Module["noExitRuntime"]||true;var stackRestore=val=>__emscripten_stack_restore(val);var stackSave=()=>_emscripten_stack_get_current();var UTF8Decoder=typeof TextDecoder!="undefined"?new TextDecoder:undefined;var UTF8ArrayToString=(heapOrArray,idx=0,maxBytesToRead=NaN)=>{var endIdx=idx+maxBytesToRead;var endPtr=idx;while(heapOrArray[endPtr]&&!(endPtr>=endIdx))++endPtr;if(endPtr-idx>16&&heapOrArray.buffer&&UTF8Decoder){return UTF8Decoder.decode(heapOrArray.subarray(idx,endPtr))}var str="";while(idx<endPtr){var u0=heapOrArray[idx++];if(!(u0&128)){str+=String.fromCharCode(u0);continue}var u1=heapOrArray[idx++]&63;if((u0&224)==192){str+=String.fromCharCode((u0&31)<<6|u1);continue}var u2=heapOrArray[idx++]&63;if((u0&240)==224){u0=(u0&15)<<12|u1<<6|u2}else{u0=(u0&7)<<18|u1<<12|u2<<6|heapOrArray[idx++]&63}if(u0<65536){str+=String.fromCharCode(u0)}else{var ch=u0-65536;str+=String.fromCharCode(55296|ch>>10,56320|ch&1023)}}return str};var UTF8ToString=(ptr,maxBytesToRead)=>ptr?UTF8ArrayToString(HEAPU8,ptr,maxBytesToRead):"";var ___assert_fail=(condition,filename,line,func)=>abort(`Assertion failed: ${UTF8ToString(condition)}, at: `+[filename?UTF8ToString(filename):"unknown filename",line,func?UTF8ToString(func):"unknown function"]);class ExceptionInfo{constructor(excPtr){this.excPtr=excPtr;this.ptr=excPtr-24}set_type(type){HEAPU32[this.ptr+4>>2]=type}get_type(){return HEAPU32[this.ptr+4>>2]}set_destructor(destructor){HEAPU32[this.ptr+8>>2]=destructor}get_destructor(){return HEAPU32[this.ptr+8>>2]}set_caught(caught){caught=caught?1:0;HEAP8[this.ptr+12]=caught}get_caught(){return HEAP8[this.ptr+12]!=0}set_rethrown(rethrown){rethrown=rethrown?1:0;HEAP8[this.ptr+13]=rethrown}get_rethrown(){return HEAP8[this.ptr+13]!=0}init(type,destructor){this.set_adjusted_ptr(0);this.set_type(type);this.set_destructor(destructor)}set_adjusted_ptr(adjustedPtr){HEAPU32[this.ptr+16>>2]=adjustedPtr}get_adjusted_ptr(){return HEAPU32[this.ptr+16>>2]}}var exceptionLast=0;var uncaughtExceptionCount=0;var ___cxa_throw=(ptr,type,destructor)=>{var info=new ExceptionInfo(ptr);info.init(type,destructor);exceptionLast=ptr;uncaughtExceptionCount++;throw exceptionLast};var SYSCALLS={varargs:undefined,getStr(ptr){var ret=UTF8ToString(ptr);return ret}};function ___syscall_fcntl64(fd,cmd,varargs){SYSCALLS.varargs=varargs;return 0}function ___syscall_ioctl(fd,op,varargs){SYSCALLS.varargs=varargs;return 0}function ___syscall_openat(dirfd,path,flags,varargs){SYSCALLS.varargs=varargs}var __abort_js=()=>abort("");var stringToUTF8Array=(str,heap,outIdx,maxBytesToWrite)=>{if(!(maxBytesToWrite>0))return 0;var startIdx=outIdx;var endIdx=outIdx+maxBytesToWrite-1;for(var i=0;i<str.length;++i){var u=str.charCodeAt(i);if(u>=55296&&u<=57343){var u1=str.charCodeAt(++i);u=65536+((u&1023)<<10)|u1&1023}if(u<=127){if(outIdx>=endIdx)break;heap[outIdx++]=u}else if(u<=2047){if(outIdx+1>=endIdx)break;heap[outIdx++]=192|u>>6;heap[outIdx++]=128|u&63}else if(u<=65535){if(outIdx+2>=endIdx)break;heap[outIdx++]=224|u>>12;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}else{if(outIdx+3>=endIdx)break;heap[outIdx++]=240|u>>18;heap[outIdx++]=128|u>>12&63;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}}heap[outIdx]=0;return outIdx-startIdx};var stringToUTF8=(str,outPtr,maxBytesToWrite)=>stringToUTF8Array(str,HEAPU8,outPtr,maxBytesToWrite);var __tzset_js=(timezone,daylight,std_name,dst_name)=>{var currentYear=(new Date).getFullYear();var winter=new Date(currentYear,0,1);var summer=new Date(currentYear,6,1);var winterOffset=winter.getTimezoneOffset();var summerOffset=summer.getTimezoneOffset();var stdTimezoneOffset=Math.max(winterOffset,summerOffset);HEAPU32[timezone>>2]=stdTimezoneOffset*60;HEAP32[daylight>>2]=Number(winterOffset!=summerOffset);var extractZone=timezoneOffset=>{var sign=timezoneOffset>=0?"-":"+";var absOffset=Math.abs(timezoneOffset);var hours=String(Math.floor(absOffset/60)).padStart(2,"0");var minutes=String(absOffset%60).padStart(2,"0");return`UTC${sign}${hours}${minutes}`};var winterName=extractZone(winterOffset);var summerName=extractZone(summerOffset);if(summerOffset<winterOffset){stringToUTF8(winterName,std_name,17);stringToUTF8(summerName,dst_name,17)}else{stringToUTF8(winterName,dst_name,17);stringToUTF8(summerName,std_name,17)}};var readEmAsmArgsArray=[];var readEmAsmArgs=(sigPtr,buf)=>{readEmAsmArgsArray.length=0;var ch;while(ch=HEAPU8[sigPtr++]){var wide=ch!=105;wide&=ch!=112;buf+=wide&&buf%8?4:0;readEmAsmArgsArray.push(ch==112?HEAPU32[buf>>2]:ch==106?HEAP64[buf>>3]:ch==105?HEAP32[buf>>2]:HEAPF64[buf>>3]);buf+=wide?8:4}return readEmAsmArgsArray};var runEmAsmFunction=(code,sigPtr,argbuf)=>{var args=readEmAsmArgs(sigPtr,argbuf);return ASM_CONSTS[code](...args)};var _emscripten_asm_const_int=(code,sigPtr,argbuf)=>runEmAsmFunction(code,sigPtr,argbuf);var getHeapMax=()=>2147483648;var alignMemory=(size,alignment)=>Math.ceil(size/alignment)*alignment;var growMemory=size=>{var b=wasmMemory.buffer;var pages=(size-b.byteLength+65535)/65536|0;try{wasmMemory.grow(pages);updateMemoryViews();return 1}catch(e){}};var _emscripten_resize_heap=requestedSize=>{var oldSize=HEAPU8.length;requestedSize>>>=0;var maxHeapSize=getHeapMax();if(requestedSize>maxHeapSize){return false}for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignMemory(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=growMemory(newSize);if(replacement){return true}}return false};var ENV={};var getExecutableName=()=>thisProgram||"./this.program";var getEnvStrings=()=>{if(!getEnvStrings.strings){var lang=(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8";var env={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:lang,_:getExecutableName()};for(var x in ENV){if(ENV[x]===undefined)delete env[x];else env[x]=ENV[x]}var strings=[];for(var x in env){strings.push(`${x}=${env[x]}`)}getEnvStrings.strings=strings}return getEnvStrings.strings};var stringToAscii=(str,buffer)=>{for(var i=0;i<str.length;++i){HEAP8[buffer++]=str.charCodeAt(i)}HEAP8[buffer]=0};var _environ_get=(__environ,environ_buf)=>{var bufSize=0;getEnvStrings().forEach((string,i)=>{var ptr=environ_buf+bufSize;HEAPU32[__environ+i*4>>2]=ptr;stringToAscii(string,ptr);bufSize+=string.length+1});return 0};var _environ_sizes_get=(penviron_count,penviron_buf_size)=>{var strings=getEnvStrings();HEAPU32[penviron_count>>2]=strings.length;var bufSize=0;strings.forEach(string=>bufSize+=string.length+1);HEAPU32[penviron_buf_size>>2]=bufSize;return 0};var runtimeKeepaliveCounter=0;var keepRuntimeAlive=()=>noExitRuntime||runtimeKeepaliveCounter>0;var _proc_exit=code=>{EXITSTATUS=code;if(!keepRuntimeAlive()){Module["onExit"]?.(code);ABORT=true}quit_(code,new ExitStatus(code))};var exitJS=(status,implicit)=>{EXITSTATUS=status;_proc_exit(status)};var _exit=exitJS;var _fd_close=fd=>52;var _fd_read=(fd,iov,iovcnt,pnum)=>52;var INT53_MAX=9007199254740992;var INT53_MIN=-9007199254740992;var bigintToI53Checked=num=>num<INT53_MIN||num>INT53_MAX?NaN:Number(num);function _fd_seek(fd,offset,whence,newOffset){offset=bigintToI53Checked(offset);return 70}var printCharBuffers=[null,[],[]];var printChar=(stream,curr)=>{var buffer=printCharBuffers[stream];if(curr===0||curr===10){(stream===1?out:err)(UTF8ArrayToString(buffer));buffer.length=0}else{buffer.push(curr)}};var _fd_write=(fd,iov,iovcnt,pnum)=>{var num=0;for(var i=0;i<iovcnt;i++){var ptr=HEAPU32[iov>>2];var len=HEAPU32[iov+4>>2];iov+=8;for(var j=0;j<len;j++){printChar(fd,HEAPU8[ptr+j])}num+=len}HEAPU32[pnum>>2]=num;return 0};var getCFunc=ident=>{var func=Module["_"+ident];return func};var writeArrayToMemory=(array,buffer)=>{HEAP8.set(array,buffer)};var lengthBytesUTF8=str=>{var len=0;for(var i=0;i<str.length;++i){var c=str.charCodeAt(i);if(c<=127){len++}else if(c<=2047){len+=2}else if(c>=55296&&c<=57343){len+=4;++i}else{len+=3}}return len};var stackAlloc=sz=>__emscripten_stack_alloc(sz);var stringToUTF8OnStack=str=>{var size=lengthBytesUTF8(str)+1;var ret=stackAlloc(size);stringToUTF8(str,ret,size);return ret};var ccall=(ident,returnType,argTypes,args,opts)=>{var toC={string:str=>{var ret=0;if(str!==null&&str!==undefined&&str!==0){ret=stringToUTF8OnStack(str)}return ret},array:arr=>{var ret=stackAlloc(arr.length);writeArrayToMemory(arr,ret);return ret}};function convertReturnValue(ret){if(returnType==="string"){return UTF8ToString(ret)}if(returnType==="boolean")return Boolean(ret);return ret}var func=getCFunc(ident);var cArgs=[];var stack=0;if(args){for(var i=0;i<args.length;i++){var converter=toC[argTypes[i]];if(converter){if(stack===0)stack=stackSave();cArgs[i]=converter(args[i])}else{cArgs[i]=args[i]}}}var ret=func(...cArgs);function onDone(ret){if(stack!==0)stackRestore(stack);return convertReturnValue(ret)}ret=onDone(ret);return ret};var cwrap=(ident,returnType,argTypes,opts)=>{var numericArgs=!argTypes||argTypes.every(type=>type==="number"||type==="boolean");var numericRet=returnType!=="string";if(numericRet&&numericArgs&&!opts){return getCFunc(ident)}return(...args)=>ccall(ident,returnType,argTypes,args,opts)};var wasmImports={a:___assert_fail,b:___cxa_throw,g:___syscall_fcntl64,i:___syscall_ioctl,j:___syscall_openat,l:__abort_js,k:__tzset_js,d:_emscripten_asm_const_int,m:_emscripten_resize_heap,o:_environ_get,p:_environ_sizes_get,c:_exit,e:_fd_close,h:_fd_read,n:_fd_seek,f:_fd_write};var wasmExports=await createWasm();var ___wasm_call_ctors=wasmExports["r"];var _c4w_create_proof_ctx=Module["_c4w_create_proof_ctx"]=wasmExports["s"];var _c4w_free_proof_ctx=Module["_c4w_free_proof_ctx"]=wasmExports["t"];var _c4w_execute_proof_ctx=Module["_c4w_execute_proof_ctx"]=wasmExports["u"];var _c4w_req_set_response=Module["_c4w_req_set_response"]=wasmExports["v"];var _c4w_req_set_error=Module["_c4w_req_set_error"]=wasmExports["w"];var _c4w_create_verify_ctx=Module["_c4w_create_verify_ctx"]=wasmExports["x"];var _c4w_free_verify_ctx=Module["_c4w_free_verify_ctx"]=wasmExports["y"];var _free=Module["_free"]=wasmExports["z"];var _c4w_get_method_type=Module["_c4w_get_method_type"]=wasmExports["A"];var _c4w_verify_proof=Module["_c4w_verify_proof"]=wasmExports["B"];var _c4w_req_free=Module["_c4w_req_free"]=wasmExports["C"];var _c4w_buffer_alloc=Module["_c4w_buffer_alloc"]=wasmExports["D"];var _init_storage=Module["_init_storage"]=wasmExports["E"];var _malloc=Module["_malloc"]=wasmExports["G"];var __emscripten_stack_restore=wasmExports["H"];var __emscripten_stack_alloc=wasmExports["I"];var _emscripten_stack_get_current=wasmExports["J"];Module["ccall"]=ccall;Module["cwrap"]=cwrap;Module["UTF8ToString"]=UTF8ToString;Module["stringToUTF8"]=stringToUTF8;function run(){if(runDependencies>0){dependenciesFulfilled=run;return}preRun();if(runDependencies>0){dependenciesFulfilled=run;return}function doRun(){Module["calledRun"]=true;if(ABORT)return;initRuntime();readyPromiseResolve(Module);Module["onRuntimeInitialized"]?.();postRun()}if(Module["setStatus"]){Module["setStatus"]("Running...");setTimeout(()=>{setTimeout(()=>Module["setStatus"](""),1);doRun()},1)}else{doRun()}}if(Module["preInit"]){if(typeof Module["preInit"]=="function")Module["preInit"]=[Module["preInit"]];while(Module["preInit"].length>0){Module["preInit"].pop()()}}run();moduleRtn=readyPromise;
|
|
8
|
+
var Module=moduleArg;var readyPromiseResolve,readyPromiseReject;var readyPromise=new Promise((resolve,reject)=>{readyPromiseResolve=resolve;readyPromiseReject=reject});var ENVIRONMENT_IS_WEB=typeof window=="object";var ENVIRONMENT_IS_WORKER=typeof WorkerGlobalScope!="undefined";var ENVIRONMENT_IS_NODE=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string"&&process.type!="renderer";var moduleOverrides=Object.assign({},Module);var arguments_=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var readAsync,readBinary;if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){if(ENVIRONMENT_IS_WORKER){scriptDirectory=self.location.href}else if(typeof document!="undefined"&&document.currentScript){scriptDirectory=document.currentScript.src}if(_scriptName){scriptDirectory=_scriptName}if(scriptDirectory.startsWith("blob:")){scriptDirectory=""}else{scriptDirectory=scriptDirectory.slice(0,scriptDirectory.replace(/[?#].*/,"").lastIndexOf("/")+1)}{if(ENVIRONMENT_IS_WORKER){readBinary=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=async url=>{var response=await fetch(url,{credentials:"same-origin"});if(response.ok){return response.arrayBuffer()}throw new Error(response.status+" : "+response.url)}}}else{}var out=Module["print"]||console.log.bind(console);var err=Module["printErr"]||console.error.bind(console);Object.assign(Module,moduleOverrides);moduleOverrides=null;if(Module["arguments"])arguments_=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];var wasmBinary=Module["wasmBinary"];var wasmMemory;var ABORT=false;var EXITSTATUS;var HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAP64,HEAPU64,HEAPF64;var runtimeInitialized=false;function updateMemoryViews(){var b=wasmMemory.buffer;Module["HEAP8"]=HEAP8=new Int8Array(b);Module["HEAP16"]=HEAP16=new Int16Array(b);Module["HEAPU8"]=HEAPU8=new Uint8Array(b);Module["HEAPU16"]=HEAPU16=new Uint16Array(b);Module["HEAP32"]=HEAP32=new Int32Array(b);Module["HEAPU32"]=HEAPU32=new Uint32Array(b);Module["HEAPF32"]=HEAPF32=new Float32Array(b);Module["HEAPF64"]=HEAPF64=new Float64Array(b);Module["HEAP64"]=HEAP64=new BigInt64Array(b);Module["HEAPU64"]=HEAPU64=new BigUint64Array(b)}function preRun(){if(Module["preRun"]){if(typeof Module["preRun"]=="function")Module["preRun"]=[Module["preRun"]];while(Module["preRun"].length){addOnPreRun(Module["preRun"].shift())}}callRuntimeCallbacks(onPreRuns)}function initRuntime(){runtimeInitialized=true;wasmExports["r"]()}function postRun(){if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"].length){addOnPostRun(Module["postRun"].shift())}}callRuntimeCallbacks(onPostRuns)}var runDependencies=0;var dependenciesFulfilled=null;function addRunDependency(id){runDependencies++;Module["monitorRunDependencies"]?.(runDependencies)}function removeRunDependency(id){runDependencies--;Module["monitorRunDependencies"]?.(runDependencies);if(runDependencies==0){if(dependenciesFulfilled){var callback=dependenciesFulfilled;dependenciesFulfilled=null;callback()}}}function abort(what){Module["onAbort"]?.(what);what="Aborted("+what+")";err(what);ABORT=true;what+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(what);readyPromiseReject(e);throw e}var wasmBinaryFile;function findWasmBinary(){if(Module["locateFile"]){return locateFile("c4w.wasm")}return new URL("c4w.wasm",import.meta.url).href}function getBinarySync(file){if(file==wasmBinaryFile&&wasmBinary){return new Uint8Array(wasmBinary)}if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}async function getWasmBinary(binaryFile){if(!wasmBinary){try{var response=await readAsync(binaryFile);return new Uint8Array(response)}catch{}}return getBinarySync(binaryFile)}async function instantiateArrayBuffer(binaryFile,imports){try{var binary=await getWasmBinary(binaryFile);var instance=await WebAssembly.instantiate(binary,imports);return instance}catch(reason){err(`failed to asynchronously prepare wasm: ${reason}`);abort(reason)}}async function instantiateAsync(binary,binaryFile,imports){if(!binary&&typeof WebAssembly.instantiateStreaming=="function"){try{var response=fetch(binaryFile,{credentials:"same-origin"});var instantiationResult=await WebAssembly.instantiateStreaming(response,imports);return instantiationResult}catch(reason){err(`wasm streaming compile failed: ${reason}`);err("falling back to ArrayBuffer instantiation")}}return instantiateArrayBuffer(binaryFile,imports)}function getWasmImports(){return{a:wasmImports}}async function createWasm(){function receiveInstance(instance,module){wasmExports=instance.exports;wasmMemory=wasmExports["q"];updateMemoryViews();removeRunDependency("wasm-instantiate");return wasmExports}addRunDependency("wasm-instantiate");function receiveInstantiationResult(result){return receiveInstance(result["instance"])}var info=getWasmImports();if(Module["instantiateWasm"]){return new Promise((resolve,reject)=>{Module["instantiateWasm"](info,(mod,inst)=>{receiveInstance(mod,inst);resolve(mod.exports)})})}wasmBinaryFile??=findWasmBinary();try{var result=await instantiateAsync(wasmBinary,wasmBinaryFile,info);var exports=receiveInstantiationResult(result);return exports}catch(e){readyPromiseReject(e);return Promise.reject(e)}}var ASM_CONSTS={166284:($0,$1)=>{var keyStr=UTF8ToString($0);var data=Module.storage.get(keyStr);if(data){var bufferPtr=_c4w_buffer_alloc($1,data.length);HEAPU8.set(data,bufferPtr);return 1}return 0},166472:($0,$1,$2)=>{var keyStr=UTF8ToString($0);var array=new Uint8Array($2);array.set(HEAPU8.subarray($1,$1+$2));Module.storage.set(keyStr,array)},166615:$0=>{var keyStr=UTF8ToString($0);Module.storage.del(keyStr)}};class ExitStatus{name="ExitStatus";constructor(status){this.message=`Program terminated with exit(${status})`;this.status=status}}var callRuntimeCallbacks=callbacks=>{while(callbacks.length>0){callbacks.shift()(Module)}};var onPostRuns=[];var addOnPostRun=cb=>onPostRuns.unshift(cb);var onPreRuns=[];var addOnPreRun=cb=>onPreRuns.unshift(cb);var noExitRuntime=Module["noExitRuntime"]||true;var stackRestore=val=>__emscripten_stack_restore(val);var stackSave=()=>_emscripten_stack_get_current();var UTF8Decoder=typeof TextDecoder!="undefined"?new TextDecoder:undefined;var UTF8ArrayToString=(heapOrArray,idx=0,maxBytesToRead=NaN)=>{var endIdx=idx+maxBytesToRead;var endPtr=idx;while(heapOrArray[endPtr]&&!(endPtr>=endIdx))++endPtr;if(endPtr-idx>16&&heapOrArray.buffer&&UTF8Decoder){return UTF8Decoder.decode(heapOrArray.subarray(idx,endPtr))}var str="";while(idx<endPtr){var u0=heapOrArray[idx++];if(!(u0&128)){str+=String.fromCharCode(u0);continue}var u1=heapOrArray[idx++]&63;if((u0&224)==192){str+=String.fromCharCode((u0&31)<<6|u1);continue}var u2=heapOrArray[idx++]&63;if((u0&240)==224){u0=(u0&15)<<12|u1<<6|u2}else{u0=(u0&7)<<18|u1<<12|u2<<6|heapOrArray[idx++]&63}if(u0<65536){str+=String.fromCharCode(u0)}else{var ch=u0-65536;str+=String.fromCharCode(55296|ch>>10,56320|ch&1023)}}return str};var UTF8ToString=(ptr,maxBytesToRead)=>ptr?UTF8ArrayToString(HEAPU8,ptr,maxBytesToRead):"";var ___assert_fail=(condition,filename,line,func)=>abort(`Assertion failed: ${UTF8ToString(condition)}, at: `+[filename?UTF8ToString(filename):"unknown filename",line,func?UTF8ToString(func):"unknown function"]);class ExceptionInfo{constructor(excPtr){this.excPtr=excPtr;this.ptr=excPtr-24}set_type(type){HEAPU32[this.ptr+4>>2]=type}get_type(){return HEAPU32[this.ptr+4>>2]}set_destructor(destructor){HEAPU32[this.ptr+8>>2]=destructor}get_destructor(){return HEAPU32[this.ptr+8>>2]}set_caught(caught){caught=caught?1:0;HEAP8[this.ptr+12]=caught}get_caught(){return HEAP8[this.ptr+12]!=0}set_rethrown(rethrown){rethrown=rethrown?1:0;HEAP8[this.ptr+13]=rethrown}get_rethrown(){return HEAP8[this.ptr+13]!=0}init(type,destructor){this.set_adjusted_ptr(0);this.set_type(type);this.set_destructor(destructor)}set_adjusted_ptr(adjustedPtr){HEAPU32[this.ptr+16>>2]=adjustedPtr}get_adjusted_ptr(){return HEAPU32[this.ptr+16>>2]}}var exceptionLast=0;var uncaughtExceptionCount=0;var ___cxa_throw=(ptr,type,destructor)=>{var info=new ExceptionInfo(ptr);info.init(type,destructor);exceptionLast=ptr;uncaughtExceptionCount++;throw exceptionLast};var SYSCALLS={varargs:undefined,getStr(ptr){var ret=UTF8ToString(ptr);return ret}};function ___syscall_fcntl64(fd,cmd,varargs){SYSCALLS.varargs=varargs;return 0}function ___syscall_ioctl(fd,op,varargs){SYSCALLS.varargs=varargs;return 0}function ___syscall_openat(dirfd,path,flags,varargs){SYSCALLS.varargs=varargs}var __abort_js=()=>abort("");var stringToUTF8Array=(str,heap,outIdx,maxBytesToWrite)=>{if(!(maxBytesToWrite>0))return 0;var startIdx=outIdx;var endIdx=outIdx+maxBytesToWrite-1;for(var i=0;i<str.length;++i){var u=str.charCodeAt(i);if(u>=55296&&u<=57343){var u1=str.charCodeAt(++i);u=65536+((u&1023)<<10)|u1&1023}if(u<=127){if(outIdx>=endIdx)break;heap[outIdx++]=u}else if(u<=2047){if(outIdx+1>=endIdx)break;heap[outIdx++]=192|u>>6;heap[outIdx++]=128|u&63}else if(u<=65535){if(outIdx+2>=endIdx)break;heap[outIdx++]=224|u>>12;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}else{if(outIdx+3>=endIdx)break;heap[outIdx++]=240|u>>18;heap[outIdx++]=128|u>>12&63;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}}heap[outIdx]=0;return outIdx-startIdx};var stringToUTF8=(str,outPtr,maxBytesToWrite)=>stringToUTF8Array(str,HEAPU8,outPtr,maxBytesToWrite);var __tzset_js=(timezone,daylight,std_name,dst_name)=>{var currentYear=(new Date).getFullYear();var winter=new Date(currentYear,0,1);var summer=new Date(currentYear,6,1);var winterOffset=winter.getTimezoneOffset();var summerOffset=summer.getTimezoneOffset();var stdTimezoneOffset=Math.max(winterOffset,summerOffset);HEAPU32[timezone>>2]=stdTimezoneOffset*60;HEAP32[daylight>>2]=Number(winterOffset!=summerOffset);var extractZone=timezoneOffset=>{var sign=timezoneOffset>=0?"-":"+";var absOffset=Math.abs(timezoneOffset);var hours=String(Math.floor(absOffset/60)).padStart(2,"0");var minutes=String(absOffset%60).padStart(2,"0");return`UTC${sign}${hours}${minutes}`};var winterName=extractZone(winterOffset);var summerName=extractZone(summerOffset);if(summerOffset<winterOffset){stringToUTF8(winterName,std_name,17);stringToUTF8(summerName,dst_name,17)}else{stringToUTF8(winterName,dst_name,17);stringToUTF8(summerName,std_name,17)}};var readEmAsmArgsArray=[];var readEmAsmArgs=(sigPtr,buf)=>{readEmAsmArgsArray.length=0;var ch;while(ch=HEAPU8[sigPtr++]){var wide=ch!=105;wide&=ch!=112;buf+=wide&&buf%8?4:0;readEmAsmArgsArray.push(ch==112?HEAPU32[buf>>2]:ch==106?HEAP64[buf>>3]:ch==105?HEAP32[buf>>2]:HEAPF64[buf>>3]);buf+=wide?8:4}return readEmAsmArgsArray};var runEmAsmFunction=(code,sigPtr,argbuf)=>{var args=readEmAsmArgs(sigPtr,argbuf);return ASM_CONSTS[code](...args)};var _emscripten_asm_const_int=(code,sigPtr,argbuf)=>runEmAsmFunction(code,sigPtr,argbuf);var getHeapMax=()=>2147483648;var alignMemory=(size,alignment)=>Math.ceil(size/alignment)*alignment;var growMemory=size=>{var b=wasmMemory.buffer;var pages=(size-b.byteLength+65535)/65536|0;try{wasmMemory.grow(pages);updateMemoryViews();return 1}catch(e){}};var _emscripten_resize_heap=requestedSize=>{var oldSize=HEAPU8.length;requestedSize>>>=0;var maxHeapSize=getHeapMax();if(requestedSize>maxHeapSize){return false}for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignMemory(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=growMemory(newSize);if(replacement){return true}}return false};var ENV={};var getExecutableName=()=>thisProgram||"./this.program";var getEnvStrings=()=>{if(!getEnvStrings.strings){var lang=(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8";var env={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:lang,_:getExecutableName()};for(var x in ENV){if(ENV[x]===undefined)delete env[x];else env[x]=ENV[x]}var strings=[];for(var x in env){strings.push(`${x}=${env[x]}`)}getEnvStrings.strings=strings}return getEnvStrings.strings};var stringToAscii=(str,buffer)=>{for(var i=0;i<str.length;++i){HEAP8[buffer++]=str.charCodeAt(i)}HEAP8[buffer]=0};var _environ_get=(__environ,environ_buf)=>{var bufSize=0;getEnvStrings().forEach((string,i)=>{var ptr=environ_buf+bufSize;HEAPU32[__environ+i*4>>2]=ptr;stringToAscii(string,ptr);bufSize+=string.length+1});return 0};var _environ_sizes_get=(penviron_count,penviron_buf_size)=>{var strings=getEnvStrings();HEAPU32[penviron_count>>2]=strings.length;var bufSize=0;strings.forEach(string=>bufSize+=string.length+1);HEAPU32[penviron_buf_size>>2]=bufSize;return 0};var runtimeKeepaliveCounter=0;var keepRuntimeAlive=()=>noExitRuntime||runtimeKeepaliveCounter>0;var _proc_exit=code=>{EXITSTATUS=code;if(!keepRuntimeAlive()){Module["onExit"]?.(code);ABORT=true}quit_(code,new ExitStatus(code))};var exitJS=(status,implicit)=>{EXITSTATUS=status;_proc_exit(status)};var _exit=exitJS;var _fd_close=fd=>52;var _fd_read=(fd,iov,iovcnt,pnum)=>52;var INT53_MAX=9007199254740992;var INT53_MIN=-9007199254740992;var bigintToI53Checked=num=>num<INT53_MIN||num>INT53_MAX?NaN:Number(num);function _fd_seek(fd,offset,whence,newOffset){offset=bigintToI53Checked(offset);return 70}var printCharBuffers=[null,[],[]];var printChar=(stream,curr)=>{var buffer=printCharBuffers[stream];if(curr===0||curr===10){(stream===1?out:err)(UTF8ArrayToString(buffer));buffer.length=0}else{buffer.push(curr)}};var _fd_write=(fd,iov,iovcnt,pnum)=>{var num=0;for(var i=0;i<iovcnt;i++){var ptr=HEAPU32[iov>>2];var len=HEAPU32[iov+4>>2];iov+=8;for(var j=0;j<len;j++){printChar(fd,HEAPU8[ptr+j])}num+=len}HEAPU32[pnum>>2]=num;return 0};var getCFunc=ident=>{var func=Module["_"+ident];return func};var writeArrayToMemory=(array,buffer)=>{HEAP8.set(array,buffer)};var lengthBytesUTF8=str=>{var len=0;for(var i=0;i<str.length;++i){var c=str.charCodeAt(i);if(c<=127){len++}else if(c<=2047){len+=2}else if(c>=55296&&c<=57343){len+=4;++i}else{len+=3}}return len};var stackAlloc=sz=>__emscripten_stack_alloc(sz);var stringToUTF8OnStack=str=>{var size=lengthBytesUTF8(str)+1;var ret=stackAlloc(size);stringToUTF8(str,ret,size);return ret};var ccall=(ident,returnType,argTypes,args,opts)=>{var toC={string:str=>{var ret=0;if(str!==null&&str!==undefined&&str!==0){ret=stringToUTF8OnStack(str)}return ret},array:arr=>{var ret=stackAlloc(arr.length);writeArrayToMemory(arr,ret);return ret}};function convertReturnValue(ret){if(returnType==="string"){return UTF8ToString(ret)}if(returnType==="boolean")return Boolean(ret);return ret}var func=getCFunc(ident);var cArgs=[];var stack=0;if(args){for(var i=0;i<args.length;i++){var converter=toC[argTypes[i]];if(converter){if(stack===0)stack=stackSave();cArgs[i]=converter(args[i])}else{cArgs[i]=args[i]}}}var ret=func(...cArgs);function onDone(ret){if(stack!==0)stackRestore(stack);return convertReturnValue(ret)}ret=onDone(ret);return ret};var cwrap=(ident,returnType,argTypes,opts)=>{var numericArgs=!argTypes||argTypes.every(type=>type==="number"||type==="boolean");var numericRet=returnType!=="string";if(numericRet&&numericArgs&&!opts){return getCFunc(ident)}return(...args)=>ccall(ident,returnType,argTypes,args,opts)};var wasmImports={a:___assert_fail,b:___cxa_throw,g:___syscall_fcntl64,i:___syscall_ioctl,j:___syscall_openat,l:__abort_js,k:__tzset_js,d:_emscripten_asm_const_int,m:_emscripten_resize_heap,o:_environ_get,p:_environ_sizes_get,c:_exit,e:_fd_close,h:_fd_read,n:_fd_seek,f:_fd_write};var wasmExports=await createWasm();var ___wasm_call_ctors=wasmExports["r"];var _c4w_create_proof_ctx=Module["_c4w_create_proof_ctx"]=wasmExports["s"];var _c4w_free_proof_ctx=Module["_c4w_free_proof_ctx"]=wasmExports["t"];var _c4w_execute_proof_ctx=Module["_c4w_execute_proof_ctx"]=wasmExports["u"];var _c4w_req_set_response=Module["_c4w_req_set_response"]=wasmExports["v"];var _c4w_req_set_error=Module["_c4w_req_set_error"]=wasmExports["w"];var _c4w_create_verify_ctx=Module["_c4w_create_verify_ctx"]=wasmExports["x"];var _c4w_free_verify_ctx=Module["_c4w_free_verify_ctx"]=wasmExports["y"];var _free=Module["_free"]=wasmExports["z"];var _c4w_get_method_type=Module["_c4w_get_method_type"]=wasmExports["A"];var _c4w_verify_proof=Module["_c4w_verify_proof"]=wasmExports["B"];var _c4w_req_free=Module["_c4w_req_free"]=wasmExports["C"];var _c4w_buffer_alloc=Module["_c4w_buffer_alloc"]=wasmExports["D"];var _init_storage=Module["_init_storage"]=wasmExports["E"];var _malloc=Module["_malloc"]=wasmExports["G"];var __emscripten_stack_restore=wasmExports["H"];var __emscripten_stack_alloc=wasmExports["I"];var _emscripten_stack_get_current=wasmExports["J"];Module["ccall"]=ccall;Module["cwrap"]=cwrap;Module["UTF8ToString"]=UTF8ToString;Module["stringToUTF8"]=stringToUTF8;function run(){if(runDependencies>0){dependenciesFulfilled=run;return}preRun();if(runDependencies>0){dependenciesFulfilled=run;return}function doRun(){Module["calledRun"]=true;if(ABORT)return;initRuntime();readyPromiseResolve(Module);Module["onRuntimeInitialized"]?.();postRun()}if(Module["setStatus"]){Module["setStatus"]("Running...");setTimeout(()=>{setTimeout(()=>Module["setStatus"](""),1);doRun()},1)}else{doRun()}}if(Module["preInit"]){if(typeof Module["preInit"]=="function")Module["preInit"]=[Module["preInit"]];while(Module["preInit"].length>0){Module["preInit"].pop()()}}run();moduleRtn=readyPromise;
|
|
9
9
|
|
|
10
10
|
|
|
11
11
|
return moduleRtn;
|
package/c4w.wasm
CHANGED
|
Binary file
|
package/cjs/chains.js
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Copyright (c) 2025 corpus.core
|
|
4
|
+
*
|
|
5
|
+
* Permission is hereby granted, free of charge, to any person obtaining a copy of
|
|
6
|
+
* this software and associated documentation files (the "Software"), to deal in
|
|
7
|
+
* the Software without restriction, including without limitation the rights to
|
|
8
|
+
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
|
9
|
+
* the Software, and to permit persons to whom the Software is furnished to do so,
|
|
10
|
+
* subject to the following conditions:
|
|
11
|
+
*
|
|
12
|
+
* The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
* copies or substantial portions of the Software.
|
|
14
|
+
*
|
|
15
|
+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
|
17
|
+
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
|
18
|
+
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
|
19
|
+
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
|
20
|
+
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
21
|
+
*
|
|
22
|
+
* SPDX-License-Identifier: MIT
|
|
23
|
+
*/
|
|
24
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
25
|
+
exports.getChainConfig = exports.resolveChainId = exports.defaultChainConfig = exports.default_config = void 0;
|
|
26
|
+
exports.get_chain_id = get_chain_id;
|
|
27
|
+
exports.chain_conf = chain_conf;
|
|
28
|
+
exports.default_config = {
|
|
29
|
+
'1': {
|
|
30
|
+
alias: ["mainnet", "eth", "0x1"],
|
|
31
|
+
beacon_apis: ["https://lodestar-mainnet.chainsafe.io"],
|
|
32
|
+
rpcs: ["https://rpc.ankr.com/eth"],
|
|
33
|
+
prover: ["https://mainnet1.colibri-proof.tech"],
|
|
34
|
+
checkpointz: [], //"https://sync-mainnet.beaconcha.in", "https://beaconstate.info", "https://sync.invis.tools", "https://beaconstate.ethstaker.cc"],
|
|
35
|
+
pollingInterval: 12000,
|
|
36
|
+
},
|
|
37
|
+
'11155111': {
|
|
38
|
+
alias: ["sepolia", "0xaa36a7"],
|
|
39
|
+
beacon_apis: ["https://ethereum-sepolia-beacon-api.publicnode.com"],
|
|
40
|
+
rpcs: ["https://ethereum-sepolia-rpc.publicnode.com"],
|
|
41
|
+
prover: ["https://sepolia.colibri-proof.tech"],
|
|
42
|
+
checkpointz: [], // No public checkpointz for Sepolia yet
|
|
43
|
+
pollingInterval: 12000,
|
|
44
|
+
},
|
|
45
|
+
'100': {
|
|
46
|
+
alias: ["gnosis", "xdai", "0x64"],
|
|
47
|
+
beacon_apis: ["https://gnosis.colibri-proof.tech"],
|
|
48
|
+
rpcs: ["https://rpc.ankr.com/gnosis"],
|
|
49
|
+
prover: ["https://gnosis.colibri-proof.tech"],
|
|
50
|
+
checkpointz: [], // TODO: Add Gnosis checkpointz servers
|
|
51
|
+
pollingInterval: 5000,
|
|
52
|
+
},
|
|
53
|
+
'10200': {
|
|
54
|
+
alias: ["chiado", "0x27d8"],
|
|
55
|
+
beacon_apis: ["https://gnosis-chiado-beacon-api.publicnode.com"],
|
|
56
|
+
rpcs: ["https://gnosis-chiado-rpc.publicnode.com"],
|
|
57
|
+
prover: ["https://chiado.colibri-proof.tech"],
|
|
58
|
+
checkpointz: [], // No public checkpointz for Chiado yet
|
|
59
|
+
pollingInterval: 5000,
|
|
60
|
+
},
|
|
61
|
+
};
|
|
62
|
+
function get_chain_id(chain_id) {
|
|
63
|
+
const chain_id_num = parseInt(chain_id);
|
|
64
|
+
if (!isNaN(chain_id_num))
|
|
65
|
+
return chain_id_num;
|
|
66
|
+
for (const chain in exports.default_config) {
|
|
67
|
+
if (exports.default_config[chain].alias.includes(chain_id))
|
|
68
|
+
return parseInt(chain);
|
|
69
|
+
}
|
|
70
|
+
throw new Error("Invalid chain id: " + chain_id);
|
|
71
|
+
}
|
|
72
|
+
function chain_conf(config, chainId) {
|
|
73
|
+
const k = config?.chains?.[chainId];
|
|
74
|
+
if (k)
|
|
75
|
+
return k;
|
|
76
|
+
const k2 = exports.default_config[chainId + ''];
|
|
77
|
+
if (k2)
|
|
78
|
+
return k2;
|
|
79
|
+
return undefined;
|
|
80
|
+
}
|
|
81
|
+
// Friendly aliases (optional, keep compatibility with planned naming)
|
|
82
|
+
exports.defaultChainConfig = exports.default_config;
|
|
83
|
+
exports.resolveChainId = get_chain_id;
|
|
84
|
+
exports.getChainConfig = chain_conf;
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Copyright (c) 2025 corpus.core
|
|
4
|
+
*
|
|
5
|
+
* Permission is hereby granted, free of charge, to any person obtaining a copy of
|
|
6
|
+
* this software and associated documentation files (the "Software"), to deal in
|
|
7
|
+
* the Software without restriction, including without limitation the rights to
|
|
8
|
+
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
|
9
|
+
* the Software, and to permit persons to whom the Software is furnished to do so,
|
|
10
|
+
* subject to the following conditions:
|
|
11
|
+
*
|
|
12
|
+
* The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
* copies or substantial portions of the Software.
|
|
14
|
+
*
|
|
15
|
+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
|
17
|
+
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
|
18
|
+
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
|
19
|
+
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
|
20
|
+
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
21
|
+
*
|
|
22
|
+
* SPDX-License-Identifier: MIT
|
|
23
|
+
*/
|
|
24
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
25
|
+
exports.ConnectionState = void 0;
|
|
26
|
+
const types_js_1 = require("./types.js");
|
|
27
|
+
// Helper function for chain ID formatting - intentionally kept separate for now
|
|
28
|
+
// If this function is *only* used by ConnectionState, it could be moved inside or made local.
|
|
29
|
+
// However, C4Client.rpc also uses it for its LOCAL eth_chainId case, so it might need broader access.
|
|
30
|
+
// For this refactoring, we assume it's passed in or globally accessible if needed elsewhere.
|
|
31
|
+
// Helper function for chain ID formatting (can be used by ConnectionManager and C4Client)
|
|
32
|
+
function formatChainId(value, debug) {
|
|
33
|
+
if (typeof value === 'string') {
|
|
34
|
+
if (value.startsWith('0x')) {
|
|
35
|
+
return value.toLowerCase();
|
|
36
|
+
}
|
|
37
|
+
const parsed = parseInt(value, 10);
|
|
38
|
+
if (!isNaN(parsed)) {
|
|
39
|
+
return '0x' + parsed.toString(16);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
else if (typeof value === 'number') {
|
|
43
|
+
return '0x' + value.toString(16);
|
|
44
|
+
}
|
|
45
|
+
if (debug) {
|
|
46
|
+
console.warn('Could not format chainId:', value);
|
|
47
|
+
}
|
|
48
|
+
return null;
|
|
49
|
+
}
|
|
50
|
+
class ConnectionState {
|
|
51
|
+
_isConnected = false;
|
|
52
|
+
_currentChainId = null;
|
|
53
|
+
_initialConnectionAttempted = false;
|
|
54
|
+
config;
|
|
55
|
+
fetchRpcChainIdCallback;
|
|
56
|
+
eventEmitter;
|
|
57
|
+
constructor(config, fetchRpcChainIdCallback, eventEmitter) {
|
|
58
|
+
this.config = config;
|
|
59
|
+
this.fetchRpcChainIdCallback = fetchRpcChainIdCallback;
|
|
60
|
+
this.eventEmitter = eventEmitter;
|
|
61
|
+
this._currentChainId = formatChainId(this.config.chainId, this.config.debug);
|
|
62
|
+
}
|
|
63
|
+
get isConnected() {
|
|
64
|
+
return this._isConnected;
|
|
65
|
+
}
|
|
66
|
+
get currentChainId() {
|
|
67
|
+
return this._currentChainId;
|
|
68
|
+
}
|
|
69
|
+
get initialConnectionAttempted() {
|
|
70
|
+
return this._initialConnectionAttempted;
|
|
71
|
+
}
|
|
72
|
+
async attemptInitialConnection() {
|
|
73
|
+
if (this._initialConnectionAttempted)
|
|
74
|
+
return;
|
|
75
|
+
this._initialConnectionAttempted = true;
|
|
76
|
+
if (this.config.debug) {
|
|
77
|
+
console.log('[CS] Attempting initial connection...');
|
|
78
|
+
}
|
|
79
|
+
try {
|
|
80
|
+
const result = await this.fetchRpcChainIdCallback();
|
|
81
|
+
const formattedChainId = formatChainId(result, this.config.debug);
|
|
82
|
+
if (formattedChainId) {
|
|
83
|
+
this._isConnected = true;
|
|
84
|
+
this._currentChainId = formattedChainId;
|
|
85
|
+
if (this.config.debug) {
|
|
86
|
+
console.log('[CS] Initial connection successful. ChainId:', this._currentChainId);
|
|
87
|
+
}
|
|
88
|
+
this.eventEmitter.emit('connect', { chainId: this._currentChainId });
|
|
89
|
+
}
|
|
90
|
+
else {
|
|
91
|
+
this._isConnected = false;
|
|
92
|
+
if (this.config.debug) {
|
|
93
|
+
console.warn('[CS] Initial eth_chainId did not return a valid format or was null:', result, ". Client remains disconnected but uses configured chainId.");
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
catch (error) {
|
|
98
|
+
this._isConnected = false;
|
|
99
|
+
if (this.config.debug) {
|
|
100
|
+
console.error('[CS] Initial connection check failed:', error);
|
|
101
|
+
if (error instanceof types_js_1.ProviderRpcError) {
|
|
102
|
+
console.error('[CS] ProviderRpcError during initial connection check:', error.code, error.message);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
processSuccessfulRequest(requestMethod, requestResult) {
|
|
108
|
+
if (!this._isConnected) {
|
|
109
|
+
this._isConnected = true;
|
|
110
|
+
const updateAndEmitConnect = async () => {
|
|
111
|
+
let determinedChainId = null;
|
|
112
|
+
if (requestMethod === 'eth_chainId') {
|
|
113
|
+
determinedChainId = formatChainId(requestResult, this.config.debug);
|
|
114
|
+
}
|
|
115
|
+
else {
|
|
116
|
+
try {
|
|
117
|
+
const chainIdResult = await this.fetchRpcChainIdCallback();
|
|
118
|
+
determinedChainId = formatChainId(chainIdResult, this.config.debug);
|
|
119
|
+
}
|
|
120
|
+
catch (e) {
|
|
121
|
+
if (this.config.debug)
|
|
122
|
+
console.warn('[CS] Failed to fetch chainId for connect event, using current _currentChainId as fallback.', e);
|
|
123
|
+
determinedChainId = this._currentChainId;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
this._currentChainId = determinedChainId || formatChainId(this.config.chainId, this.config.debug);
|
|
127
|
+
this.eventEmitter.emit('connect', { chainId: this._currentChainId });
|
|
128
|
+
};
|
|
129
|
+
updateAndEmitConnect().catch(err => {
|
|
130
|
+
if (this.config.debug)
|
|
131
|
+
console.error("[CS] Error during background processing for connect event:", err);
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
else if (requestMethod === 'eth_chainId') {
|
|
135
|
+
const newChainId = formatChainId(requestResult, this.config.debug);
|
|
136
|
+
if (newChainId && this._currentChainId !== newChainId) {
|
|
137
|
+
const oldChainId = this._currentChainId;
|
|
138
|
+
this._currentChainId = newChainId;
|
|
139
|
+
if (this.config.debug) {
|
|
140
|
+
console.log('[CS] ChainId changed from', oldChainId, 'to', this._currentChainId);
|
|
141
|
+
}
|
|
142
|
+
this.eventEmitter.emit('chainChanged', this._currentChainId);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
processFailedRequest(error) {
|
|
147
|
+
if (error.code === 4900 && this._isConnected) {
|
|
148
|
+
this._isConnected = false;
|
|
149
|
+
if (this.config.debug) {
|
|
150
|
+
console.log('[CS] Disconnected due to error 4900.');
|
|
151
|
+
}
|
|
152
|
+
this.eventEmitter.emit('disconnect', error);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
exports.ConnectionState = ConnectionState;
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Copyright (c) 2025 corpus.core
|
|
4
|
+
*
|
|
5
|
+
* Permission is hereby granted, free of charge, to any person obtaining a copy of
|
|
6
|
+
* this software and associated documentation files (the "Software"), to deal in
|
|
7
|
+
* the Software without restriction, including without limitation the rights to
|
|
8
|
+
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
|
9
|
+
* the Software, and to permit persons to whom the Software is furnished to do so,
|
|
10
|
+
* subject to the following conditions:
|
|
11
|
+
*
|
|
12
|
+
* The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
* copies or substantial portions of the Software.
|
|
14
|
+
*
|
|
15
|
+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
|
17
|
+
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
|
18
|
+
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
|
19
|
+
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
|
20
|
+
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
21
|
+
*
|
|
22
|
+
* SPDX-License-Identifier: MIT
|
|
23
|
+
*/
|
|
24
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
25
|
+
exports.EventEmitter = void 0;
|
|
26
|
+
class EventEmitter {
|
|
27
|
+
listeners = {};
|
|
28
|
+
on(event, callback) {
|
|
29
|
+
if (!this.listeners[event]) {
|
|
30
|
+
this.listeners[event] = [];
|
|
31
|
+
}
|
|
32
|
+
this.listeners[event].push(callback);
|
|
33
|
+
return this;
|
|
34
|
+
}
|
|
35
|
+
removeListener(event, callback) {
|
|
36
|
+
if (this.listeners[event]) {
|
|
37
|
+
this.listeners[event] = this.listeners[event].filter(listener => listener !== callback);
|
|
38
|
+
}
|
|
39
|
+
return this;
|
|
40
|
+
}
|
|
41
|
+
emit(event, data) {
|
|
42
|
+
if (this.listeners[event]) {
|
|
43
|
+
this.listeners[event].forEach(listener => {
|
|
44
|
+
try {
|
|
45
|
+
listener(data);
|
|
46
|
+
}
|
|
47
|
+
catch (e) {
|
|
48
|
+
console.error(`Error in event listener for ${event}:`, e);
|
|
49
|
+
}
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
exports.EventEmitter = EventEmitter;
|
package/cjs/http.js
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.fetch_from_servers = fetch_from_servers;
|
|
4
|
+
exports.fetch_rpc = fetch_rpc;
|
|
5
|
+
exports.handle_request = handle_request;
|
|
6
|
+
/**
|
|
7
|
+
* Copyright (c) 2025 corpus.core
|
|
8
|
+
*
|
|
9
|
+
* Permission is hereby granted, free of charge, to any person obtaining a copy of
|
|
10
|
+
* this software and associated documentation files (the "Software"), to deal in
|
|
11
|
+
* the Software without restriction, including without limitation the rights to
|
|
12
|
+
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
|
13
|
+
* the Software, and to permit persons to whom the Software is furnished to do so,
|
|
14
|
+
* subject to the following conditions:
|
|
15
|
+
*
|
|
16
|
+
* The above copyright notice and this permission notice shall be included in all
|
|
17
|
+
* copies or substantial portions of the Software.
|
|
18
|
+
*
|
|
19
|
+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
20
|
+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
|
21
|
+
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
|
22
|
+
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
|
23
|
+
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
|
24
|
+
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
25
|
+
*
|
|
26
|
+
* SPDX-License-Identifier: MIT
|
|
27
|
+
*/
|
|
28
|
+
const wasm_js_1 = require("./wasm.js");
|
|
29
|
+
function joinPath(base, path) {
|
|
30
|
+
if (!path)
|
|
31
|
+
return base;
|
|
32
|
+
if (!path.length)
|
|
33
|
+
return base;
|
|
34
|
+
return base + (path.startsWith('/') ? path : '/' + path);
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* @param servers List of base URLs
|
|
38
|
+
* @param path Optional path to append to server URL
|
|
39
|
+
* @param method HTTP method
|
|
40
|
+
* @param payload Optional JSON payload (POST)
|
|
41
|
+
* @param accept Response type hint
|
|
42
|
+
* @param excludeMask Bitmask to skip servers by index
|
|
43
|
+
* @return Uint8Array of response bytes and nodeIndex used
|
|
44
|
+
*/
|
|
45
|
+
async function fetch_from_servers(servers, path, method, payload, accept = 'json', excludeMask = 0) {
|
|
46
|
+
let lastError = 'All nodes failed';
|
|
47
|
+
let nodeIndex = 0;
|
|
48
|
+
for (const server of servers) {
|
|
49
|
+
if (excludeMask & (1 << nodeIndex)) {
|
|
50
|
+
nodeIndex++;
|
|
51
|
+
continue;
|
|
52
|
+
}
|
|
53
|
+
try {
|
|
54
|
+
const response = await fetch(joinPath(server, path), {
|
|
55
|
+
method,
|
|
56
|
+
body: payload ? JSON.stringify(payload) : undefined,
|
|
57
|
+
headers: {
|
|
58
|
+
'Content-Type': 'application/json',
|
|
59
|
+
'Accept': accept === 'json' ? 'application/json' : 'application/octet-stream',
|
|
60
|
+
},
|
|
61
|
+
});
|
|
62
|
+
if (!response.ok) {
|
|
63
|
+
lastError = `HTTP error! Status: ${response.status}, Details: ${await response.text()}`;
|
|
64
|
+
nodeIndex++;
|
|
65
|
+
continue;
|
|
66
|
+
}
|
|
67
|
+
const bytes = await response.blob().then(b => b.arrayBuffer());
|
|
68
|
+
return { data: new Uint8Array(bytes), nodeIndex };
|
|
69
|
+
}
|
|
70
|
+
catch (e) {
|
|
71
|
+
lastError = (e instanceof Error) ? e.message : String(e);
|
|
72
|
+
}
|
|
73
|
+
nodeIndex++;
|
|
74
|
+
}
|
|
75
|
+
throw new Error(lastError);
|
|
76
|
+
}
|
|
77
|
+
// --- Higher level helpers used by Colibri client ---
|
|
78
|
+
function log(msg) {
|
|
79
|
+
console.error(msg);
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Posts a JSON-RPC payload across multiple URLs and returns result or proof bytes.
|
|
83
|
+
* @param urls Ordered list of RPC endpoints
|
|
84
|
+
* @param payload JSON-RPC payload (id will be set to 1 if not provided)
|
|
85
|
+
* @param as_proof Expect octet-stream (true) or JSON result (false)
|
|
86
|
+
* @return result value for JSON or raw bytes for proofs
|
|
87
|
+
*/
|
|
88
|
+
async function fetch_rpc(urls, payload, as_proof = false) {
|
|
89
|
+
let last_error = 'All nodes failed';
|
|
90
|
+
for (const url of urls) {
|
|
91
|
+
const response = await fetch(url, {
|
|
92
|
+
method: 'POST',
|
|
93
|
+
body: JSON.stringify({ id: 1, jsonrpc: '2.0', ...payload }),
|
|
94
|
+
headers: {
|
|
95
|
+
'Content-Type': 'application/json',
|
|
96
|
+
'Accept': as_proof ? 'application/octet-stream' : 'application/json',
|
|
97
|
+
},
|
|
98
|
+
});
|
|
99
|
+
if (response.ok) {
|
|
100
|
+
if (!as_proof) {
|
|
101
|
+
const res = await response.json();
|
|
102
|
+
if (res.error) {
|
|
103
|
+
last_error = res.error?.message || res.error;
|
|
104
|
+
continue;
|
|
105
|
+
}
|
|
106
|
+
return res.result;
|
|
107
|
+
}
|
|
108
|
+
const bytes = await response.blob().then(blob => blob.arrayBuffer());
|
|
109
|
+
return new Uint8Array(bytes);
|
|
110
|
+
}
|
|
111
|
+
else {
|
|
112
|
+
last_error = `HTTP error! Status: ${response.status}, Details: ${await response.text()}`;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
throw new Error(last_error);
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Handles a C4 data request by fetching from configured servers, setting the
|
|
119
|
+
* response or error back into the C context, and leveraging cache if present.
|
|
120
|
+
* @param req DataRequest descriptor from C
|
|
121
|
+
* @param conf Colibri configuration
|
|
122
|
+
*/
|
|
123
|
+
async function handle_request(req, conf) {
|
|
124
|
+
const free_buffers = [];
|
|
125
|
+
let servers = [];
|
|
126
|
+
switch (req.type) {
|
|
127
|
+
case 'checkpointz':
|
|
128
|
+
servers = [...(conf.checkpointz || []), ...(conf.beacon_apis || []), ...(conf.prover || [])];
|
|
129
|
+
break;
|
|
130
|
+
case 'beacon_api':
|
|
131
|
+
servers = [...(conf.beacon_apis || []), ...(conf.prover || [])];
|
|
132
|
+
break;
|
|
133
|
+
case 'prover':
|
|
134
|
+
servers = [...(conf.prover || [])];
|
|
135
|
+
break;
|
|
136
|
+
default:
|
|
137
|
+
servers = conf.rpcs || [...((conf.prover || []).map(p => p + (p.endsWith('/') ? '' : '/') + 'unverified_rpc'))];
|
|
138
|
+
break;
|
|
139
|
+
}
|
|
140
|
+
const c4w = await (0, wasm_js_1.getC4w)();
|
|
141
|
+
let path = (req.type == 'eth_rpc' && req.payload)
|
|
142
|
+
? `rpc: ${req.payload?.method}(${req.payload?.params.join(',')})`
|
|
143
|
+
: req.url;
|
|
144
|
+
let cacheable = conf.cache && conf.cache.cacheable(req);
|
|
145
|
+
if (cacheable && conf.cache) {
|
|
146
|
+
const data = conf.cache.get(req);
|
|
147
|
+
if (data) {
|
|
148
|
+
if (conf.debug)
|
|
149
|
+
log(`::: ${path} (len=${data.length} bytes) CACHED`);
|
|
150
|
+
c4w._c4w_req_set_response(req.req_ptr, (0, wasm_js_1.copy_to_c)(data, c4w), data.length, 0);
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
try {
|
|
155
|
+
const accept = req.encoding == 'json' ? 'json' : 'octet';
|
|
156
|
+
const { data, nodeIndex } = await fetch_from_servers(servers, req.url || '', req.method, req.payload, accept, req.exclude_mask);
|
|
157
|
+
c4w._c4w_req_set_response(req.req_ptr, (0, wasm_js_1.copy_to_c)(data, c4w), data.length, nodeIndex);
|
|
158
|
+
if (conf.debug)
|
|
159
|
+
log(`::: ${path} (len=${data.length} bytes) FETCHED`);
|
|
160
|
+
if (conf.cache && cacheable)
|
|
161
|
+
conf.cache.set(req, data);
|
|
162
|
+
}
|
|
163
|
+
catch (e) {
|
|
164
|
+
const last_error = (e instanceof Error) ? e.message : String(e);
|
|
165
|
+
c4w._c4w_req_set_error(req.req_ptr, (0, wasm_js_1.as_char_ptr)(last_error, c4w, free_buffers), 0);
|
|
166
|
+
if (conf.debug)
|
|
167
|
+
log(`::: ${path} (Error: ${last_error})`);
|
|
168
|
+
}
|
|
169
|
+
finally {
|
|
170
|
+
free_buffers.forEach(ptr => c4w._free(ptr));
|
|
171
|
+
}
|
|
172
|
+
}
|