@erc7824/nitrolite
Version:
The Nitrolite SDK empowers developers to build high-performance, scalable web3 applications using state channels. It's designed to provide near-instant transactions and significantly improved user experiences by minimizing direct blockchain interactions.
57 lines (56 loc) • 2.01 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.getPackedState = getPackedState;
exports.getStateHash = getStateHash;
exports.getPackedChallengeState = getPackedChallengeState;
exports.getChallengeHash = getChallengeHash;
exports.verifySignature = verifySignature;
const viem_1 = require("viem");
function getPackedState(channelId, state) {
return (0, viem_1.encodeAbiParameters)([
{ name: 'channelId', type: 'bytes32' },
{
name: 'intent',
type: 'uint8',
},
{
name: 'version',
type: 'uint256',
},
{ name: 'data', type: 'bytes' },
{
name: 'allocations',
type: 'tuple[]',
components: [
{ name: 'destination', type: 'address' },
{ name: 'token', type: 'address' },
{ name: 'amount', type: 'uint256' },
],
},
], [channelId, state.intent, state.version, state.data, state.allocations]);
}
function getStateHash(channelId, state) {
return (0, viem_1.keccak256)(getPackedState(channelId, state));
}
function getPackedChallengeState(channelId, state) {
const packedState = getPackedState(channelId, state);
const encoded = (0, viem_1.encodePacked)(['bytes', 'string'], [packedState, 'challenge']);
return encoded;
}
function getChallengeHash(channelId, state) {
return (0, viem_1.keccak256)(getPackedChallengeState(channelId, state));
}
async function verifySignature(channelId, state, signature, expectedSigner) {
try {
const stateHash = getStateHash(channelId, state);
const recoveredAddress = await (0, viem_1.recoverMessageAddress)({
message: { raw: stateHash },
signature: signature,
});
return recoveredAddress.toLowerCase() === expectedSigner.toLowerCase();
}
catch (error) {
console.error('Signature verification failed:', error);
return false;
}
}