UNPKG

swapnet-sdk-test-4

Version:
87 lines (86 loc) 2.37 kB
import { toBeHex } from "ethers"; const removeLeadingZero = (hexString)=>{ if (!hexString.startsWith('0x')) { throw new Error(`Invalid hex string ${hexString}!`); } if (hexString.charAt(2) === '0') { return `0x${hexString.slice(3)}`; } return hexString; }; export class AddressAsIf { address; _field; _slot; _value; _registeredPromises; constructor(address){ this.address = address; this._field = undefined; this._slot = undefined; this._value = undefined; this._registeredPromises = []; } balance() { this._field = "balance"; return this; } nonce() { this._field = "nonce"; return this; } code() { this._field = "code"; return this; } stateDiff(slot) { this._field = "stateDiff"; this._slot = slot; return this; } state(slot) { this._field = "state"; this._slot = slot; return this; } is(value) { if (this._field === "balance" || this._field === "nonce") { if (typeof value !== 'bigint') { throw new Error(`Invalid value type for field ${this._field}.`); } this._value = removeLeadingZero(toBeHex(value)); return this; } this._value = value.toString(); return this; } async valueAsync() { await Promise.all(this._registeredPromises); if (this._field === undefined) { throw new Error(`Field of AsIf at ${this.address} is not set!`); } if (this._value === undefined) { throw new Error(`Value of AsIf at ${this.address} is not set!`); } if (this._field === "stateDiff" || this._field === "state") { if (this._slot === undefined) { throw new Error(`StateDiff slot of AsIf at ${this.address} is not set!`); } return { [this.address]: { [this._field]: { [this._slot]: this._value } } }; } return { [this.address]: { [this._field]: this._value } }; } } export const addressAt = (address)=>{ return new AddressAsIf(address); };