UNPKG

swapnet-sdk-test-4

Version:
61 lines (60 loc) 2.7 kB
import { keccak256, solidityPacked, toBeHex, zeroPadValue } from "ethers"; import { AddressAsIf } from "./addressAsIf.js"; const getAllowanceSlotKey = (ownerAddress, tokenAddress, spenderAddress, mappingSlotNumber)=>{ return keccak256(zeroPadValue(spenderAddress, 32) + keccak256(zeroPadValue(tokenAddress, 32) + keccak256(zeroPadValue(ownerAddress, 32) + toBeHex(mappingSlotNumber, 32).slice(2)).slice(2)).slice(2)); }; const getNonceBitmapSlotKey = (ownerAddress, wordPos, mappingSlotNumber)=>{ return keccak256(toBeHex(wordPos, 32) + keccak256(zeroPadValue(ownerAddress, 32) + toBeHex(mappingSlotNumber, 32).slice(2)).slice(2)); }; export class Permit2AsIf extends AddressAsIf { _method = undefined; _allowanceMappingSlotNumber = 1; _nonceBitmapMappingSlotNumber = 0; constructor(address){ super(address); } allowance(ownerAddress, tokenAddress, spenderAddress) { this._method = "allowance"; super.stateDiff(getAllowanceSlotKey(ownerAddress, tokenAddress, spenderAddress, this._allowanceMappingSlotNumber)); return this; } nonceBitmap(ownerAddress, wordPos) { this._method = "nonceBitmap"; const nonceBitmapSlotKey = getNonceBitmapSlotKey(ownerAddress, wordPos, this._nonceBitmapMappingSlotNumber); // console.log(`Calculated nonceBitmapSlotKey is ${nonceBitmapSlotKey}`); super.stateDiff(nonceBitmapSlotKey); return this; } is(value) { if (this._method === undefined) { throw new Error(`Method to call of AsIf at ${this.address} is not set!`); } if (this._method === "allowance") { if (value === undefined || typeof value !== 'object' || typeof value.amount !== 'bigint' || typeof value.expiration !== 'bigint' || typeof value.nonce !== 'bigint') { throw new Error(`Invalid value for ${this._method} of Permit2AsIf.`); } const slotValue = solidityPacked([ "uint48", "uint48", "uint160" ], [ value.nonce, value.expiration, value.amount ]); super.is(slotValue); } else if (this._method === "nonceBitmap") { if (value === undefined || typeof value !== 'bigint') { throw new Error(`Invalid value for ${this._method} of Permit2AsIf.`); } const slotValue = solidityPacked([ "uint" ], [ value ]); super.is(slotValue); } return this; } } export const permit2 = (permit2Address)=>new Permit2AsIf(permit2Address);