Skip to main content

Provisioning a serverless function

Oyster Serverless is built using the workerd sandbox which is built using the V8 engine. Therefore, it supports JS and WASM based workers natively. By extension, any language that compiles or transpiles down to JS or WASM can be used as well.

The testnet deployment of Oyster Serverless currently only supports JS code files that are embedded as service workers in the sandbox. Support for more elaborate and flexible ways of deployment are under development.

Code structure​

The worker code should contain one single script file that uses addEventListener to register handlers. The most common handler is the fetch handler that is triggered on every request.

Here is an example that performs factorization of the number provided.

addEventListener('fetch', event => {
event.respondWith(handle(event.request));
});

async function handle(request) {
try {
const data = await request.json();
console.log(data);

let num = data.num;
let factors = [];
let divisor = 2;
if(typeof num != 'number') {
return new Response(`Please provide a valid integer as input in the format {'num':10}`);
}

while (num > 2) {
if (num % divisor === 0) {
factors.push(divisor);
num /= divisor;
} else {
divisor++;
}
}

if(factors.length == 0) {
return new Response('No prime factor for the provided number');
}

return new Response(factors);
} catch(err) {
console.log(err);
return new Response('Please provide a valid JSON input');
}
}

The JS code can be minified so that it costs less to provision it. For this, minify tool can be used. Here is the minimized version of example above.

addEventListener('fetch', event => {event.respondWith(handle(event.request));});async function handle(request){try{const data = await request.json();console.log(data);let num = data.num;let factors = [];let divisor = 2;if(typeof num != 'number'){return new Response(`Please provide a valid integer as input in the format{'num':10}`);}while (num > 2) {if (num % divisor === 0) {factors.push(divisor);num /= divisor;} else {divisor++;}}if(factors.length == 0){return new Response('No prime factor for the provided number');}return new Response(factors);}catch(err){console.log(err);return new Response('Please provide a valid JSON input');}}

Test Serverless Function Locally​

It is recommended to test the serverless function before provisioning it. Follow this guide to test locally.

Provisioning​

Oyster expects the code to be stored as calldata in the 0x061868A3387c5F6a875c111a2FDDEB70C66344F4 contract on the Arbitrum One chain.

Provision Code Paste the code into the saveCodeInCalldata function and create the transaction.

It should look something like this - https://arbiscan.io/tx/0x27139ece7a6558c26c3773647822837612a5159c0d757c96cc86c008466dfb7a