public static function serialize($filename, $instance, $force = false)
    {
        if ($filename == '') {
            throw new \danog\MadelineProto\Exception('Empty filename');
        }
        if ($instance->API->asyncInitPromise) {
            return $instance->call(static function () use ($filename, $instance, $force) {
                yield $instance->API->asyncInitPromise;
                $instance->API->asyncInitPromise = null;
                return self::serialize($filename, $instance, $force);
            });
        }
        if (isset($instance->API->setdem) && $instance->API->setdem) {
            $instance->API->setdem = false;
            $instance->API->__construct($instance->API->settings);
        }
        if ($instance->API === null && !$instance->getting_api_id) {
            return false;
        }
        $instance->serialized = time();
        $realpaths = self::realpaths($filename);
        if (!file_exists($realpaths['lockfile'])) {
            touch($realpaths['lockfile']);
            clearstatcache();
        }
        $realpaths['lockfile'] = fopen($realpaths['lockfile'], 'w');
        \danog\MadelineProto\Logger::log('Waiting for exclusive lock of serialization lockfile...');
        flock($realpaths['lockfile'], LOCK_EX);
        \danog\MadelineProto\Logger::log('Lock acquired, serializing');

        try {
            if (!$instance->getting_api_id) {
                $update_closure = $instance->API->settings['updates']['callback'];
                if ($instance->API->settings['updates']['callback'] instanceof \Closure) {
                    $instance->API->settings['updates']['callback'] = [$instance->API, 'noop'];
                }
                $logger_closure = $instance->API->settings['logger']['logger_param'];
                if ($instance->API->settings['logger']['logger_param'] instanceof \Closure) {
                    $instance->API->settings['logger']['logger_param'] = [$instance->API, 'noop'];
                }
            }
            $wrote = file_put_contents($realpaths['tempfile'], serialize($instance));
            rename($realpaths['tempfile'], $realpaths['file']);
        } finally {
            if (!$instance->getting_api_id) {
                $instance->API->settings['updates']['callback'] = $update_closure;
                $instance->API->settings['logger']['logger_param'] = $logger_closure;
            }
            flock($realpaths['lockfile'], LOCK_UN);
            fclose($realpaths['lockfile']);
        }

        return $wrote;
    }