PROTOTYPE: Bus Pirate/Logic Analyzer with Ice40 FPGA

Bus Pirate “Ultra” taps an iCE40 FPGA to power a combined Bus Pirate interface and logic analyzer that is infinity hackable. Previous Bus Pirates relied on the hardware peripherals available in a microcontroller, which vary in features and have the occasional bug. With an FPGA we can implement practically any peripheral with all the fixes and hacks we want! SPI, I2C, UART, CAN? Yes! Master or slave? Both! Complex frequency generator? Yup! Full featured JTAG debugger? Don’t see why not!

A big STM32F103ZE (1) microcontroller connects to an iCE40HX4K FPGA (2) through a 16bit bus that can move a ton of data. The fully buffered interface (3) is capable of high-speed signaling from 1.2volt to 5volts. 128Mbit of RAM (4) powers a logic analyzer with a potential maximum speed over 200MSPS. A 32Mbit flash chip (5) stores up to 30 bitstreams with different features that can be loaded into the FPGA by the microcontroller.

This post covers our most recent hacks to the Bus Pirate, created with these goals in mind:

  • Peripherals that work and can be hacked
  • Direct interfacing at all common voltage levels
  • Real-speed bus activity
  • Built-in logic analyzer
  • Plenty of space for updates

Continue below to read about the design, or jump to the forum to see the bleeding edge.

The Bus Pirate is a tool that talks to microchips in various protocols such as I2C and SPI. Get to know a chip first, then dive into the code. It’s been ten years since Seeed Studio did the original Bus Pirate production, and now we’re hacking new hardware for the next decade.

The Bus Pirate v3.x PCB is extremely simple due to a feature in PIC24FJ microcontrollers called Peripheral Pin Select. PPS allows most major peripherals (UART, SPI, PWM, counters, etc) to be assigned to almost any IO pin. Five PIC pins provide all the functionality for all the supported protocols.

Last year Sjaak did a deep dive on an STM32 ARM-based Bus Pirate. Unlike the PIC24FJ, all the hardware peripherals are fixed to certain pins that have to be tied together. All the interconnections make a rat nest of traces.

Once we got familiar with the STM32 it was obvious that the optimizations for low-power and DMA were going to be a real pain to work around. Take for example the I2C peripheral: you need to tell it when the transfer is ending at least one byte in advance. This is great if you’re setting up repetitive transfers using DMA in low-power modes, but the Bus Pirate is for hacking and “human scale” interactions. We faced two bad options: send a ghost byte when we can’t infer the end of a transfer, or use software I2C libraries. There’s really no point in having this much chip and then resorting to bit-banging!

Bus Pirate Ultra

We shelved the project to lick our wounds and come up with some new design goals:

  1. Peripherals that work and can be hacked
  2. Direct interfacing at all common voltage levels
  3. Real-speed bus activity
  4. Built-in logic analyzer
  5. Plenty of space for updates

Peripherals that work and can be hacked

The bottom line is we need hackable peripherals. From the I2C hardware bug in the B2 revision of the 24FJ64GA002, to the tricky implementation of peripherals in modern ARM chips, fixed silicon peripherals are a huge limitation. An FPGA is one answer.

In this design we use a Lattice ICE40 FPGA to implement bus protocol peripherals. Bugs can be squashed and features can be added with a simple bitstream update.

Source: ST app note AN2784 page 6.

The FPGA is connected to the STM32 static memory controller (FSMC) using a 16bit SRAM-like bus with 6 address bits. That’s a lot of bandwidth to push and pull data, and will eventually drastically speed up binary operations like dumping the contents of flash chips with FLASHROM.

An FPGA has always been the next logical step for the Bus Pirate, but bloated “Webpacks” and vendor tools under restrictive licenses are not hacker friendly. Fortunately, IceStorm gives us a free, open, and fast tool chain for the ICE40 FPGA.

Direct interfacing from 1.2 to 5volts

Previous Bus Pirates could interface with chips directly at 3.3volts, and from ~2volts to 5volts using pull-up resistors and open drain pin outputs. This works well for slow experimentation, but an open drain bus has real speed limitations. We want to interface directly at any common voltage.

Source: Nexperia 74LVC1T45 datasheet page 1.

74LVC1T45 is a bi-directional buffer used in cheap ARM programmer clones sold on Taobao. This buffer is a bulldozer, capable of 420Mbps at 5volts to 60Mbps at 1.5volts. It has a partial power-down feature that disables the outputs when no power supply is present to prevent backflow current into the FPGA or the device under test. TI, Nexperia and Diodes INC all manufacture a version of the 74LVC1T45. The Nexperia version works from 1.2volts to 5.0volts, while the others have a 1.65volt minimum.

74LVC1T45 has two control pins: direction and input/output. In a fixed direction bus like SPI or asynchronous serial this buffer can be put in front of any common microcontroller peripheral. However, it’s a dead end for a bidirectional bus like I2C or 1Wire because the peripheral would need to somehow manage the direction pin on a bit by bit basis. Direction handling is not a feature we’ve ever encountered on a microcontroller peripheral. The key here is to implement our own peripherals in the FPGA, and use the FPGA to manage the direction pin.

Source: Nexperia 74LVC1G07 datasheet page 1.

A 74LVC1G07 open drain output buffer is paired with each 74LVC1T45. It is also 5volt tolerant and has partial power down protection. Open drain output could be done by switching the direction pin of the 74LVC1T45, however it requires attention to timing to avoid bus contention. It’s so much easier to add a dedicated open drain driver chip.

Real-speed bus activity

At our very first New York Maker Fair (RIP) we had the chance to meet one of our maker heroes at an after party. We introduced ourselves and Maker Hero replied “The Bus Pirate is too slow” and walked away. It was crushing, but it is accurate. The Bus Pirate is slow in several ways:

  1. It is slow in terms of maximum bus speeds from the PIC running at 16MIPS
  2. It is slow in terms of time between each bus action. For each read/write/whatever the Bus Pirate sits and spits out text to the serial terminal. On a logic analyzer, as shown above, there is a very obvious delay between each command
  3. USB CDC (virtual serial port) is super easy to use, but it is slow and antiquated

Bus speeds can be increased substantially with a fast-clocked FPGA. We used the FPGA block RAM to create a bidirectional FIFO command queue. The STM32 MCU fills the command queue, then the FPGA drives the bus signaling without any delays to handle the terminal text. The MCU reads from the FPGA output queue and spits out text from a low priority background process. The fast, continuous bus activity from the FPGA is more in line with what really happens in implemented circuits.

libopencm3, the open source peripheral library we’re using with the STM32, supports multiple USB endpoints. We’ll add a USB bulk transfer endpoint that should drastically speed up binary operations like chip programming, flash read and writes, and display interfacing.

Built-in logic analyzer

A built-in logic analyzer is a top wish list item and has appeared in various prototypes in the past. While the Bus Pirate and a datasheet are enough to get a lot of chips going, there’s a decent chance we haul out the logic analyzer to get a good look at whats happening on the wires. A built-in logic analyzer that captures each command in real time makes debugging a dream.

A simple serial SRAM logic analyzer like the Logic Shrimp and Logic Pirate are quite cheap and easy to implement with PIC18/24/30 timers. Our attempt to do the same with the STM32 was less successful, but now we can drive it from the FPGA.

To ensure that the logic analyzer is reading the actual pin states, it gets a dedicated 74LVC573 input buffer that attaches to the IO header after the signal buffers.

Bus Terminal is a little Qt hack for debugging the logic analyzer and uploading FPGA bitstreams. Eventually we’ll target sigrok with a USB bulk transfer interface and driver.

Plenty of space for updates

The biggest issue we faced with Bus Pirate v3 was the lack of space. Endlessly optimizing of strings to eek out a few more bytes is annoying. Eventually we had to split the firmware into multiple parts with different features, a nightmare for users.

We want to hack and hack and hack for years in the future without running into space limitations. The huge STM32 chip has a generous amount of flash that should be sufficient for years of development.

The FPGA is another possible space crunch. Instead of the FPGA loading it’s own bitstream like the Logic Sniffer design, we used a big 32Mbit (or 64Mbit) flash chip to store multiple bitstreams in a simple file system. The STM32 loads the correct bitstream into the FPGA for each bus protocol. Bitstreams for the ICE40 4HK chip are about 135K max, so 32Mbit of flash should hold around 30 bitstreams with different features.

Hardware, firmware, software, HDL

Taking it further

The v1a board shown here was a good proof of concept, and it made it obvious where major improvements could be made in the design. Next week we’ll post about our updates to the on-board power supplies, voltage/ADC probe, and the pull-up resistors. We’re also working on a pinout label a high-resolution IPS LCD.

Check out the forum if you’d like to skip ahead and see our latest revisions.

Shenzhen to Hong Kong on High Speed Rail

excitement

Even though Shenzhen and Hong Kong are basically the same city on opposite sides of a border, it’s still a frustratingly long trip to Hong Kong Central for a Reuben at Morty’s Deli. The new high speed rail line linking downtown Shenzhen to downtown Hong Kong makes the trip in just 15 minutes. A lot of frequent travelers are hoping it just got a lot easier to eat delicious pastrami on a whim, but with all the formalities of Chinese rail will it really cut the travel time? We jumped on to find out!

futian-station-2

Futian Railway Station is two metro stops from the Huaqiangbei electronics market, in the Futian Central Business District. It’s always empty, despite being several years old and absolutely massive. Unlike most Chinese rail stations, it’s actually in the middle of the city.

futian-tickets

It usually takes less than 10 minutes to collect tickets and go through the security checks. Shenzhen North station is on the same high speed rail line, but it’s so busy that it often takes more than an hour to get into the station. Foreigners can’t use the ticket vending machines, so we had to go to the window and hand over our passports to buy tickets from a human.

futian-security

Security checks make Chinese high speed rail more like flying out of an airport. Identity check, baggage x-ray, metal detector, and finally a manual pat-down. This is where Futian station really shines – it’s so empty that security takes less than a minute. Security in Shenzhen North can take 30 minutes or more.

boarding

Everyone riding the train was super excited. It was the same atmosphere as when the A380 was a new and exciting airplane to ride. Lots of pictures and selfies.

cover

This train has the Hong Kong MTR logo on the side, and seems to serve only Futian and Kong Kong stations. There were no other passengers on the train from stations further north when we boarded.

business-cabin

Second class tickets are around $9, first class is around $15. About the same price as taking the metro.

This is the first class cabin. Some trains also have a tourist class or business class with lay-flat seats, but at $50 it seems a bit too posh for a 15 minute train ride.

speed-display

Maximum speed was around 180 km/h. The entire trip is in an underground tunnel so there’s not much to see. The WIFI didn’t seem to work, but there was 4G mobile data during the whole ride.

border

In Hong Kong there’s a joint border crossing for both Hong Kong and China. After getting off the train you go through immigration to leave China, walk a bit, then show your passport to get into Hong Kong. Chinese immigration does a customs check on the way out, every bag of any size has to go through an x-ray machine.

kowloon-west-station

Kowloon West Station is magnificent, but also a bit of a chaotic mess. It’s also not really anywhere useful, it’s a ten minute walk through malls to find a metro to Hong Kong Central.

kowloon-west-ticket-windows

Returning to Shenzhen is much less convenient. The line to purchase tickets is super long, like the line for the Hong Kong Airport McDonald’s. The line to pickup tickets purchased via apps is more reasonable, like the line for the Hong Kong Airport Popeye’s. As in China, foreigners can’t buy tickets at the vending machines. After seeing this mess we decided it would be faster and more pleasant to catch the metro back instead.

Takeaways

From our door to Morty’s Deli in Central usually takes about 1 hour and 45 minutes using a cross border bus or the metro. It took about 1 hour and 15 minutes using high speed rail. A half hour faster isn’t bad, but it also takes a lot of planning. Tickets need to be purchased in advance, timing at the station needs to be just right, and West Kowloon isn’t exactly a useful location in Hong Kong.

Coming back to Shenzhen from Hong Kong seems like it could take even longer than a bus or metro. There’s huge crowds picking up tickets for destinations all over mainland China, so ticket collection takes forever. That means arriving early to get the tickets, then extra waiting around for a scheduled train. It’s so much easier to step onto the next metro back to Shenzhen and enjoy the ride.

Even if high speed rail is consistently faster, the experience of doing it requires all the focus and planning of catching a flight at an airport. We’ll take it from Shenzhen Futian to Hong Kong in the future, but with so much planning involved it’s always going to be easier to take the metro back.

BUS PIRATE: USB Micro B connector test

header

USB Micro B is the connector of the moment, but we haven’t had a very good time working with it. The bog-standard Chinese generic Micro B connectors on Bus Pirate v5 and Bus Pirate NG1 break constantly. We tested a Micro B connector with through-hole support tabs on the latest Bus Pirate PCBs. It turned out really well.

Standard Chinese USB Micro B connector

china-standard

A ton of mom and pop factories around Shenzhen churn these out by the bucket load. It seems like a great part: ubiquitous and cheap, doesn’t require a special board slot, versions with extended leads and centering pegs are easier to hand solder. Unfortunately, every connector soldered by every member of our team has eventually decided to exit the PCB.

This connector is optimized for paste stencil and reflow soldering. Most support should come from two solder pads under the connector that are impossible to reach with a soldering iron. Maybe it could be done with hot air, or the QFN “solder from the bottom of the board through a via” hack.

Connectors with supporting through-hole tabs

usb-old-new

The generic Chinese connector (left) has six solder pads holding it to the PCB. Four can’t be reached with a soldering iron – the two under the front, and the two recessed pads at the back near the pins.

A Molex 47589-001 (right) with through-hole support tabs went into the next revision of the Bus Pirate boards. The tabs aren’t long enough to go completely through a 1.6mm PCB, but they can still be soldered in place from the top of the board. It’s much more expensive – essentially free vs $0.50 each – but we’re optimizing for hand assembly, not production.

usb-connector

Now we’re living the dream. The four tabs are really secure, and we don’t have to treat the prototype like glass. The next step is to find the most widely available Chinese equivalent.

 

 

 

How to measure laser cut length or time?

800px-Laser_cutting_snowfla

To price laser cutting online we need to extract two pieces of info from uploaded design files. The area of a box surrounding the design, called the bounding box, is the amount of material needed. The length of all the cuts in the design can be used as a rough estimate of the cutting time consumed. Here’s where we’re at…

A dirty cheap laser cut service has been “coming very soon” for far too long. We planned to take SVG files and use a friend’s script to measure the bounding box and cut lengths. Unfortunately we never found a laser cut supplier willing to take low volume/high-mix orders and provide all the pricing info to give instant quotes.

Last week a comment at Hack a Day mentioned that dirty laser cutting is taking forever. Surprised by the interest, we asked around and found some willing suppliers. However, these suppliers only accept dxf, dwg, pdf, eps, and ps formats. SVG won’t do. Now we have a supplier but no way to give instant online quotes.

Conversion

Converting to and from SVG is plagued with wrecked arcs and curves. Potential customer dissatisfaction factor is super high. Absolutely not reliable enough for a commercial service or even for pricing.

Extracting info from CAD programs

Inkscape loads all the above formats, but we were not able to extract total path length from the command line or the shell interface. Autocad.io is an online version of AutoCAD that might be able to provide the design stats and a nice rendering, but if the API is slow or busy are customers supposed to wait minutes for their quotes?

A couple CAD programs seemed promising, but eventually we couldn’t find anything that runs on Linux and can extract the stats we need via the command line.

Measuring scripts

The script that measures PCBs in our store and at DirtyPCBs combines a bit of gerber code knowledge with some math to crank out basic stats without ever loading a CAD program. A small script to extract path length and bounding box size from dxf is very doable after a quick thumb through the spec, however nothing seems to exist online.

The learning curve to implement the dxf format and the debug time to perfect it puts this in the labor of love category. It would be a blast if we really wanted to do it, but since it’s standing in the way of a dirt cheap service that will likely never turn a profit (laser cutting is cheap and common…) there’s no resources to dedicate to writing our own.

Create g-code and simulate the cut

G-code is a popular way to control CNC mills and 3D printers. A CAM processor (yes, like the one in Cadsoft Eagle) combines information about the machine, such as cut speed, with the path in the design file to create a series of cutting steps or instructions. G-code is accepted universally, much like gerber files.

Lots of existing scripts convert dxf/pdf/eps/ps files to g-code. Once the design is in g-code there are several programs that simulate the cut and estimate the cut time (or filament used, etc). This seems like the proper way to do it. As a bonus, it lays the framework to calculate cut time and difficulty for a future DirtyCNC and DirtyInjectionMolding service.

This is as far as we’ve gotten. A dozen Python scripts on github look promising, but nothing directly outputs the info we need without a bit of hacking. We’ll continue to knock together a solution in the next few days.

Please shout out in the comments if you have thoughts on any of these methods or experience with any tool chains that might work. Help us get laser cutting online and we’ll reward you with – what else – free laser cutting service!

Image source: Adam Dingley CC BY SA

HOW-TO: Add live websites to GIT without interruptions or security risks

2016-05-03_1636

Over at the DEV site we’ve been using GIT repositories hosted at BitBucket.org to push (deploy) changes to the live server instantly. It’s way slicker than uploading changed files by FTP, which has no roll back if something goes wrong. It also solves one of our China internet problems: routing to Bitbucket is much more reliable than to our servers in Germany.

It is finally time to merge the DEV site with the main Dangerous Prototypes sites – the blog got a new theme yesterday. When we started updating the rest of the site it seemed much easier and safer to put it in GIT too. There are a lot of tutorials about deploying websites with GIT, but none completely covered the process to safely put existing websites into GIT with no interruptions and maximum security.

Updating folder structure

We’re starting off with a legacy folder structure rooted in early cloud services and personal ignorance. The web root is at /var/www/. Other parts of the site (/forum, /docs) sit in subfolders of the root:

/www/ (WordPress blog)
/www/forum (phpBB forum)
/www/docs (MediaWiki wiki)

This isn’t how modern websites are structured. It’s super amateur, but it’s worked for years. We’ll change this to use Apache virtual directories when the dev site is merged with this site.

Use an external repo folder for security

“git init” would create a new repo around the entire website giving instant version control. It would also put the git config folder and files on the live web leaving a big security hole! It also binds together the five different web apps running on this server into a single giant mess.

git clone –mirror git@bitbucket.org:dangercore/wordpress.git repo-wordpress

After creating a free GIT repo at BitBucket.org called “wordpress” and setting up the SSH keys we’re really to roll. We cloned the empty repo into our home folder (~) on the server, keeping all the repo files out of the reach from the web.

cd repo-wordpress
GIT_WORK_TREE=/var/www git status

The GIT_WORK_TREE variable links the live website directory (/var/www) with the new repo in our home folder (~/repo-wordpress). The status command will show untracked files in the /var/www directory.

At this point you might think we should protect the git folders and config files with .htaccess instead of including the annoying GIT_WORK_TREE constant with every GIT command. We could, but then all changes would need to include that security for the life of the website. Blocking access is a patch against a vulnerability, better to never have the vulnerability in the first place.

.gitignore stuff

# Exclude files from the git repo
wp-content/cache/*
wp-content/media/*

# Include these files in previously blocked directories
!wp-content/media/.htaccess

#other software in root
docs/*
forum/*

Not everything belongs in our repo. 8 years of blog images and cache files take up a ton of space in a repo and we don’t need them to push code updates. We do, however, want to keep the .htaccess file in the media folder that prevents users browsing the contents of that directory.

We also want to exclude the other sites mixed into the webroot (docs/,forum/). We’ll push them into their own repos later using the same process. Put these rules in the .gitignore file in the GIT_WORK_TREE folder (/var/www for us). This is a short example .gitignore based on this, see our complete ignore files for all the sites in the forum!

GIT_WORK_TREE=/var/www git status

Check file status again. Ignored directories should not be on the list.

Add, Commit, Push

GIT_WORK_TREE=/var/www git add .

GIT is now tracking these files.

GIT_WORK_TREE=/var/www git status

See a list of the files being tracked.

GIT_WORK_TREE=/var/www git commit -m”Initial commit”

Commit the files to the local repo. Now we have a snapshot of the site code.

GIT_WORK_TREE=/var/www git push

Push from local repo to the remote repo at BitBucket. The site snapshot is now also stored at BitBucket.

Pull hooks for automatic updates

BitBucket and GitHub have a ‘hook’ feature that loads a URL after every push to the repo. We setup BitBucket to load a “secret” webpage on the server that triggers a git pull command whenever we push an update to the master branch. ServerPilot has some more info and a nice script that we modified.

Next steps

/apps/ (Folder of GIT repos)
/apps/wordpress/ (WordPress GIT repo with notes, tools, etc)
/apps/wordpress/public/ (Live public folder accessible on the web)

We want to end up with a structure where each area of the site (/forum,/docs,/blog) is an Apache virtual directory or symlink to a public subfolder inside a git repository. Instead of serving WordPress directly from the repo (/apps/wordpress/), we serve it from a subfolder inside the repo called “public” (/apps/wordpress/public).

First, this keeps the git folder and configuration files off web without the annoying GIT_WORK_TREE variable in each command. Second, we can use the main folder for other stuff that might be handy to have in the repository but shouldn’t be public: notes, database updates, sample files and data, test tools, etc.

We’re redeploying each site area like this as the new themes are finished. When the dust is settled we’ll document the final server setup that should last well into the future.

Owing DirtyPCBs: an opportunity lost

dirtyboards-sticker

With the Chinese company out of the way, I’ve had some time to work on projects and plan what to do next. One thing I have to do is own DirtyPCBs, I’ve failed at some basic stuff.

DirtyPCBs.com was a joke. It started as a quick script so our team and a few Shenzhen locals could get PCBs from our cheap fab with less hassle. A comment on a blog post said the PCB silk screen sucked, so we started calling it “Dirt cheap, dirty boards”. Unfortunately DirtyBoards.com was taken, so we stuck the site up at DirtyPCBs.com.

It stayed below radar for about 4 months, taking a couple orders a week from friends and neighbors. Then BAM! It’s on Hack a Day and suddenly getting hundreds of orders.

It isn’t a feasible business, but it’s so cool to see people actually use this thing I built. People have done some really incredible stuff with DirtyPCBs, and I’ve met a bunch of amazing hackers because of it.

Even as everything “dirty” became a common reference at Hacker Camp Shenzhen and around the BBQ joint, I kept it at arms length. I’ve been really hesitant to own it or fold it into Dangerous Prototypes. The dirty cheap PCB business model doesn’t pay for the level of support I want to offer.

I was wrong, that was a huge mistake.

Over the past two years it became a big support nightmare anyways, while also not being profitable. If we had spent that time building a DirtyPCBs community things could have been different. That doesn’t mean marketing, social media, or “community development managers” – all we needed was a forum.

This is the most basic tenant of open hardware shops. Adafruit covers it in their earliest tutorials, and I’ve talked about it at Maker Faires and accelerators.

I failed big time.

Whether we meet here in Shenzhen, or just via support email, DirtyPCBs customers are insanely awesome! For the last two years I should have brought them together to help document the service and lighten the support load. At the very least I should answer questions in a forum once, instead of every day by private email.

It’s a simple thing, and I got it wrong.

Here’s a new DirtyPCBs forum, right here at Dangerous Prototypes. Vimark and I will handle all design questions there in the future. DirtyPCBs.com has been updated with lots of crass reminders to seek help in the forum.

dpcbs-head

There are two links to the forum in the menu. “Forum”, and if you miss that, “*Help*” goes to the same place.

hcsz2015

Hacker Camp Shenzhen is another meat-space thing that’s been hard to bring online. Hacker camp gets a forum too, and I’ll handle future camp questions there. Also open for general Shenzhen trip help.

The Chinese company and Dangercore have been all-consuming monster projects. The worst seems to be over. It’s great to be back blogging a couple times a week and documenting what we’re working on. I think we have some really freaking exciting (and buggy) stuff coming, but DirtyPCBs has been an uncomfortable reminder that small stuff makes a huge difference in the long run.

HOW TO: Chinese work permit and residency visa

work-permit-book

First we started a Chinese company, then we got a bank account and import export permit. The last major thing is a work permit and residency visa.

Americans, Canadians, and soon Australians, all get an automatic 10 year multiple entry visas for China. Its quite common for foreigners to post up in China for years on a business or tourist visa.

In practice China seems quite happy to have creative professional foreigners on extended stays. As long as you have a valid visa, don’t over stay, and don’t do something stupid like teach English without a work permit, things are fine. We’ve never heard of anyone being turned away at the border for extended stays.

All that could soon be a thing of the past though, thanks to one of China’s classic pragmatic solutions. A PCB factory once told us that the city government wanted them to move to a new industrial park. Rather than use eminent domain or zoning changes, the city increased the price of water in their neighborhood and offered free water at the industrial park. They moved happily.

Recent developments in the visa situation seem similar. Last year the immigration department linked databases with the tax office. Rather than set confusing 90 days in/out rules like Europe, we can only assume China is preparing to send a tax bills to foreigners who stay long enough to trigger it under dual taxation treaties. The problem solves itself.

While there’s a gray area for foreigners doing extended business in China, a work permit and residency permit are mandatory to run a Chinese company. Standard agent fee is 5000RMB ($900USD). Everyone said it should take a month, our crap agent took almost 4 months – but gave us a generous 100RMB ($16USD) discount. As with the import export license, we just handed over the main company licenses and stamps to get started.

The final chapter of this harrowing experience follows below.

Employment licensework-permit

The employment license certificate is the first step. Fill out a simple online application with name and passport number, pick up the license the next day. Our agent took two weeks to get it done.

Health checkhealth-check

China can be a bit rough, and immigration wants to make sure you don’t show up with tuberculosis or another debilitating problem that loads the medical system.

Health checks are done at a dedicated clinic with brand new European and Japanese medical equipment. In a whirlwind of efficiency, we walked down a single hallway to get a chest x ray, heart rhythm check, ultrasound of every major organ, and a full urine and blood workup. All in about 15 minutes! While the equipment was new and shiny, it isn’t clear how well the results were read.

Total cost was 200RMB ($33USD), but we paid another 400RMB ($66USD) to get the report the next day instead of next week.

Photo receipt

photo-reciept

As with most visas we needed to include a photo. The photographer has to submit the image to a government website for verification, so be sure to get proof of that.

Employment permit

work-permit-book

This little passport book is the employment permit, it is separate and distinct from the employment license. Evidently it has to be updated at the employment office every year, by hand, in pen. A photo is simply stapled to one page. Not exactly forgery proof.

Invitation from authorized unit

invite-1

Most nationals can get a single or dual entry Chinese visa with a stamped letter from a company. For some, and for longer term visas, a special invitation letter from an “authorized unit” is required.

This is an official invitation stamped by the government. The company applies to the Shenzhen government, the government researches the company and individual, then issues the official invitation. This takes a couple weeks and its not cheap, but the actual cost is hidden in our agent fees so we can’t tell you the exact amount.

Join the visa train

secondpassport

In the first post we highly recommend a second passport for anyone attempting a Chinese company. Your passport will be gone for months at a time, and likely you will still need to travel (even if only to leave China on a visa run).

Even with the second passport, here is the series of steps we took to get the residency permit.

Business visa

visa-1

This is a 10 year business visa, now available to Americans, Canadians, and soon, Australians. We used Sunshine Travel Agency on the 41st floor of the China Services Building in Hong Kong. Drop off before 10am and pick up same day after 5pm. 5000HKD ($700USD) in total, sure beats standing in line downstairs.

Note to anyone reading this: do not assume you can get a visa in Hong Kong. Most people cannot. Until very recently Americans could not. Even if you can, the agency wants a BRAND NEW PASSPORT or warns it will be rejected by the Chinese embassy. Remember, you MUST enter Hong Kong on the passport that needs a visa and submit the “landing slip” from immigration.

Work visa

visa-2

Submit the employment license, authorized unit invitation letter, and a visa application form to the consulate in your home country. Despite what know-nothing sleazebag agents say, most (western nationals…) don’t need to appear in person. This means you can FedEx your second passport and application to an agency, then travel Malaysia and Thailand for a week while its processed and returned.

We FedEx’d it from Hong Kong, spent a few days in South East Asia, then for purely unrelated reasons went to the US. The agency, China Visa Service Center, was way more responsive than our old processor. They actually managed to divert the visa to us in Seattle on a 24 hour layover, saving an extra night in Hong Kong. Total cost for rush service and shipping was around $600USD.

Work visa is good for a single entry, unlimited stay. However, you have to apply for the residency permit within 30 days.

Residency permit

visa-3

Disappointingly, the residency permit is not a green card (or pink card). Its just another visa in the passport. Show up to the police station and turn over the passport and a short application form.

The officer asked three questions: What is your name? Where have you been in China? Have you worked in China before? Its different for everyone, but contrary to what every scumbag agent told us ad nauseam, nobody asked for a bribe or made it difficult. It was simple and easy.

Pickup was about 10 days later. We had to pay a 400RMB ($66USD) fee that had already been included in the agent fees. Agents suck.

Register address

registration

Finally, register your home address and residency permit with the local police station. Everyone is required to do this within 24 hours in China, if you stay in a hotel they do it for you. In practice the police in Shenzhen will openly tell you not to bother unless you want to buy a house, a car, or get a driver’s license*.

Registration is simple, but frustrating because nobody seems to know how to do it. The first time they gave up and let us sit at the computer to fill in our own info. Be sure to take a bunch of copies of your passport, visa, entry stamp, and possibly a photo, just to make things faster. If you want to make your Chinese name official, register it now (we found out later).

The real deal. Documented here

That’s “it”. Dangerous Prototypes INC is a functioning Chinese company with all the legit paperwork and permits. It took a year and we almost gave up a dozen times, but we made it out the other side alive.

Watch out for phonies! Always get a copy of a sourcing agent’s import export license, and verify the company online. Comments on our previous post make it clear that gray market sourcing agents in China are effecting the larger open hardware industry.

A future post titled “Shenzhen as Hollywood for Makers…but not always in a good way” has some pointed thoughts on this trend. There’s an analogy of which we’re quite fond that includes turning tricks in the alley for drugs…

Wrap-up

Residency positions us well for the new three year permanent residency permit offered to high tech and skilled “foreign experts”. While permanent residency in China isn’t an immediate goal, a Chinese ID is they key to using eChannel immigration lanes and train ticket vending machines.

drivers-license

*Next time we get a Chinese driver’s license! Without cheating!

HOW TO: China import/export permit and company bank

import-export

Last week we described the painful process of opening a Chinese company. That was actually the fast and easy part. There’s still a pile of paperwork and months of waiting ahead. This week we look at the proper, and improper, ways to export from China.

A Chinese import export permit is permission to exchange foreign money to Chinese RMB, and refund sales / VAT tax on exported products. Imports, exports, and foreign currency exchange are attached to your permit number. Any trader operating in China without one is illegally exporting and violating the currency control laws, and is not a reliable supplier in our view.

Our license was handled by an agent, we literally did nothing but hand over the company documents. It took about a month and cost around 5000RMB ($900USD). It isn’t hard to get, but is difficult to use for small scale stuff. Our giant CPA firm even botched our first attempt to get a VAT tax refund. Continue below for more on the right and wrong way to export from China, and a summary of the crisis that almost ended our Chinese company this week.

How to export from China. The legal way. 

This is the biggie. It took lots of trial and error, but to the best of our knowledge this is the proper way to export products from China and receive payment in foreign currency.

1. Receive foreign currency (USD,EUR, etc) payment by wire to the company bank account

2. Go to the bank, show an invoice for products and the import export permit

3. Money is converted to RMB. The amount and purpose is reported to government

4. Purchase products and get the official ‘fapiao’ VAT tax receipt

5. When the products leave China get a stamped export declaration form from the shipper

6. Take the VAT tax receipt and export declaration form to the tax office to rebate the 17% VAT tax. Many people skip this step. It is quite a hassle with very specific timing requirements. Unless you ship a container load of the same thing, or something very expensive, it is generally not worth the effort to get a VAT refund

7. Give the export declaration form to the accountant. The government will audit to see if the amount of currency converted to RMB matches the products exported

The tricky thing is the export declaration form. It is not a simple commercial invoice or proof of shipping. It has to come from an authorized authority with the correct stamp. It costs 300RMB ($50USD), and you need one for each package exported!

export-proof

For example a simple 5x5cm $14 Dirty PCBs order. To convert that payment to RMB to pay the factory and refund the 17% VAT we need an export declaration form that costs $50 for this order alone. Unpossible.

Why are we still doing this?

So how do you deal with this? Hong Kong company to the rescue! Instead of shipping individual orders directly to hackers from China, we export the PCBs in bulk to Dangerous Prototypes Limited Hong Kong. For a while it looked like we had to rent a warehouse in Hong Kong and hire people, but eventually we found a service to do it for us.

Xiao Tang packages PCBs into boxes and puts on all the postage labels in China. A logistics company picks up the boxes, imports them to Hong Kong as a single shipment, and drops them at the post. They charge 300RMB to handle the customs export inspection and prepare an export declaration form. Now we can exchange money to pay suppliers and refund VAT.

It seems like Seeed Studio has had to make big changes to comply with this in preparation to go IPO. Small(er) Chinese companies have a different standard of accounting and compliance requirements, but when you take a bunch of government money and prepare for public listing many more rules apply.

We’ve noticed our stuff go out of stock at Seeed a few times recently, evidently while they move between Hong Kong warehouses. Our guess is they had to ship all or most of their stock to Hong Kong to refund the VAT and get the export declaration form required to exchange currency.

We’re a WFOE, which means we are held to the highest standard from day one.

How to export from China. The wrong way.

There’s a number of loopholes and unsavory practices foreign and Chinese agents use to circumvent the currency control system.

The process we describe above is only to pay for products. Payments for services can be converted with a simple invoice. So a small Chinese company might do a production run of 100 PCBs, but bill the client for consulting services. This seems so widespread for small stuff that bankers and accountants openly encourage it.

Each individual can freely convert $50,000USD to RMB each year. According to our CPA, around 70% of foreign business with Huaqiangbei market traders is paid to the boss’ personal account. This way the boss avoids paying VAT, and they don’t need an export declaration form to convert foreign currency to RMB. We won’t pay suppliers this way until a lawyer says it is actually legal to convert funds for business. Even if it is legal, $50,000 doesn’t go far for any sizable production.

A variant on the above is to recruit Chinese people to “rent” you their yearly allotment. You wire $50,000 to their account and they keep a percentage. This is so fraught with risk and uncertainty it hardly seems like a way to run a company, but it does seem like a good way to have your money stolen…

Importing

No experience here yet, but some general observations.

The import export license can be used to import and pay taxes on stuff coming into China. For example microcontrollers. Tax is generally 17%, and can be refunded when the chips are exported in a finished product. It is a bit of a hassle, especially for a small production run, but it is very doable.

In practice, almost everyone doing production in China has some variant of a story where they smuggle chips into the country in a backpack, pants pocket, etc. Foreign engineers becoming smugglers and tax cheats, over a 17% tax that’s refundable.

Supply chains are delicate enough already, you want to throw SMUGGLING into the mix!?!? Do you want your production held up for a month while you re-source chips because you got busted smuggling them into China to cheat a 17% tax? Then DON’T SMUGGLE!

Always ask your Chinese supplier for a copy of their import export license! It is at least moderate assurance your money won’t be stolen on the way into the country, and that your products won’t be confiscated on the way out.

Open a company bank account

cmb-logo

So after months and months of work we finally have a Chinese company! But wait, it isn’t really useful with out a bank account that can convert foreign currency to RMB. This took nearly three more months.

Here’s the strange thing: Chinese banking rocks. Fees are non-existent or super duper low. Foreigners can walk in off the street, open a personal account, get an ATM card on the spot, and sign up for internet banking, all for free with a small initial deposit (~$20USD, ~120RMB).

Business banking is a whole other thing. First we went to Bank of China, cause, you know, they’re huge and international. They wanted to schedule a call in a week to setup an appointment for next month, not ok. We visited PingAn, ICBC, Communications Bank, and a few other smaller banks that weren’t even licensed to work with foreign owned companies.

Eventually we landed with China Merchant’s bank, simply because they would actually meet with us. Pro tip: choose a bank close to home or office, you or your employees will be spending a day a week there for as long as the company operates. Almost every major transaction needs to happen in person.

bank-cert

After more than a month we received permission to open a bank account from the People’s Bank Of China central banking authority. At this point the import export permit was finished and we entered another month of waiting for approvals before the account was open.

Capital injection

verification

Even with a bank account and import export license we still can’t run the damn company. We have to “inject” the 400,000RMB of capital, then convert it from USD to RMB.

operatingexpenses

The 400,000RMB in foreign currency is wired from the business owner, the HK company, to a special single-use capital injection account. When the money arrives, appear in person to convert up to 300,000RMB per day for operating expenses.

If you want to withdraw and convert capital to pay a supplier, say for PCBs, you have to submit already-paid tax receipts. Our accountant describes this as an “incomplete system”: you can only use company money to buy products, but you can’t get company money until you can prove you paid for the products and taxes. We had pay for stuff with personal money pulled from an ATM machine so we could get the tax receipts so we could get money out of the company. Which came first: the chicken or the fapiao?

Online banking

cmb

China Merchant’s Bank has reasonably workable English (likely Windows only) crapware for managing accounts. It comes with two USB certificates, one for the accounting department and one for the administrator.

Each transfer is first entered by the accounting department login, then the administrator has to login and approve. It’s pretty burdensome for a small business.

enough-fun

At least the developers seem to care about the user experience. “Check if there is enough fun”. Indeed.

For the big ones, not the small ones

One theme that keeps popping up: China is still built for big business. The plus side is a real company with real no-bull expenses and tax deductions. But, while the bank software would be great for an organization of 100+, but it stinks for a couple hackers who want to export a few PCBs. Similarly, it is easy to export a shipping container load of stuff, refund VAT, and convert payment to RMB, but you gotta hack the system to ship a $14 PCB order.

Maybe this is why such a large gray market export economy is allowed to thrive in China. Foreign and local agents are exporting products, which China encourages, but the system is incomplete and overly burdensome for small companies and individuals to be fully compliant.

A blind eye approach could be much more effective than reworking the whole system. After all, currency control largely exists to prevent big (foreign) interests from speculating and manipulating the Chinese economy. The spirit of the law isn’t to bust an eBay Arduino seller for illegal exports.

Wrap-up

For those of you following along on WeChat #shenzhen_hacker_bei, some of this might seem familiar. We reviewed our business plan with the accounting firm multiple times, but still had a moderate crisis last week.

The accountant specifically told us, in writing and on multiple occasions, that a fapiao tax receipt was sufficient to get a VAT refund. We show up with fapiaos from the PCB factory for a refund. They pull out the example export declaration form – no refund without it, and by the way, no currency conversion either. It was obvious our accountant simply had not done it before. Rather than ask the head CPA, she just parroted incorrect conventional wisdom from her colleges. Idiots.

For most of the week we thought we were tanked. After multiple visits with lawyers and accountants we pieced together the full picture described in this post, and it seemed impossible to continue without renting a Hong Kong warehouse.

Yesterday we finally found the logistics agent willing to handle the export for us and provide an export declaration form. Hopefully these extended write-ups save someone anguish in the future.

Company. Check. Import export license. Check. Bank account with money. Check and check! But wait! We still need the work permit and residency permit! Add another 2 months before we can actually run the company. More on that process next week.

 

HOW TO: Start a Chinese Company

foreign-invest-cert

While Shenzhen is becoming “Hollywood for Makers”, and not always in a good way, there don’t seem to be a lot of foreign open hardware/maker/start-up/accelerated/innovated/incubated people starting Chinese companies. As far as we know, we are the first foreign owned open hardware centric Chinese company in Shenzhen. With everything going on here, we definitely wont be the last.

There are three reasons foreigners start a Chinese company: to sell to China’s domestic market, to get legal residency, and to work with small suppliers who can’t accept foreign currency. We are only interested in the latter.

Working with a controlled currency

rmb-note

Chinese RMB is a controlled currency. Money only goes in and out of China for certain purposes, in allowed amounts, with the proper license. Most small Chinese suppliers don’t have an import/export license (and dodge taxes) so they can’t convert payments made in a foreign currency.

compression-molding

That’s why it is almost impossible for you, from abroad, to work with the small, flexible, inexpensive Chinese suppliers we have access to. If you really want to make small scale supply chain mash-ups, say 100 traffic-themed adult novelties, then tiny suppliers are crucial and they must be paid in RMB.

Our solution has always been to partner with a Chinese owned local company like Seeed Studio and FlyLin Consulting to handle our ground operation in China. Now we can pay small suppliers directly.

There are also tons of illegitimate Chinese and foreign agents in Shenzhen who do all kinds of exploitative things to circumvent the currency control system and bring money into the country. We now tell everyone: don’t work with someone in China until you see their import-export license!

Fight zombie lies

HKnotCN

Before we continue, lets take a moment to address a pervasive, zombie myth that rings constantly at every start-up meet-up in town: a Hong Kong company is NOT an alternative to a Chinese company. Despite what agents and drunken foreign start-up groupies tell you, you’re not gonna be wiring RMB into China with your new HSBC Hong Kong account.

This is so obviously false and stupid on every level – if Hong Kong had exemption to the currency control wouldn’t every rich Chinese person setup a  company to funnel money in and out? Yet everyone orbiting the start-up scene will proudly and confidently lay it out like they’re skilled insiders. Morons.

WOOF WOOF WFOE

linlin-office

Officially our company is a WFOE, a Wholly Foreign Owned Enterprise. A simpler, cheaper structure called a FIPE is becoming more common with young entrepreneurs, but we understand it to lack liability protection. Foreign Owned doesn’t refer to us, it actually refers to the Hong Kong holding company that owns the WFOE.

fapiao

WFOE is a massive beast of a company. It files a full audit report every month, it must have a minimum size office, and every single penny of expense must have a government tax receipt (fapiao, above) attached.

Its a real company and its does have some cool advantages over an US-based LLC. We draw actual salary, and personal housing is a 100% tax deductible expense for the company. Profits can be remitted to Hong Kong as dividends and taxed as capital gains, if you’re into that kinda thing. While it may take a year to setup and cost as much as a small car, there are advantages if you actually live and work and run a company in China.

Hold me tight – start a holding company

You can own a WFOE personally, but it is seriously difficult to sell shares or take on partners, and there are massive tax issues.

hong-hong-city

Instead, open a Hong Kong company first, then the Hong Kong company starts the WFOE. There are certain tax benefits for remitting profits back to the Hong Kong company, but we haven’t done it and can’t comment yet. This is our structure, and we understand it to be the same structure Seeed is now using while preparing for IPO. Image source.

The Hong Kong company is quick and easy. Setup takes a week and costs around $700-$1000USD. Supposedly you can DIY, but we tried and eventually used an agent. Beware – the Hong Kong company requires an annual audit by a CPA ($500-$1000) and a registered secretary to file the annual report ($700).

HSBC

Opening the Hong Kong company bank account is simple, but you’ll need an appointment and it will take 2-3 weeks to be approved. We use Hang Seng, but would prefer to have gone with HSBC cause, you know, they print the freaking Hong Kong money. It is helpful to take some invoices or contracts to prove you’re a real company. Monthly fees around $60.

hangseng-onlinebank

The account can hold any currency, and you can exchange between almost any currency online, pretty cool. International wires are done online and cost about $35-$40USD.

Prove you understand basic tax principals

Hong Kong has a reputation as a tax haven. Sure, if you’re a legal resident personal taxes are pretty low, but that’s not much use to a foreigner with a small business.

Corporate tax is 16.5%, but your accountant won’t let you leave profit in the company so you’ll never pay corporate tax anyways! Same with Dangerous Prototypes’ US LLC, a pass-through entity isn’t even taxed! You’ll pay personal income tax in your country of residence, however much that is. Americans are also taxed on world wide income even when paying taxes as a legal resident of a foreign country. Get it?

If someone tells you about low tax Hong Kong companies just walk away, they’re a moron.

Choose your sleazebag agent

Agents are incompetent, sleazy, misinformed, and the absolute worst part of starting a Chinese company. There’s really very little opportunity to DIY a WFOE, so you’ll have to deal with them.

We interviewed 6 agents. Initially we hired the Chinese firm that did the Hong Kong company, but they hadn’t really done a WFOE before and the requirements are too numerous and fluid to leave it in the hands of an amateur. We fired them.

Next we hired a foreign guy who always seemed to have the answers we needed. He was super slimy and went on about having face (connections) and being the fastest in town, a total turn off, but he did seem to know the process.

Our agent misguided us multiple times, delaying the formation and costing money. The agent messed up really obvious and stupid stuff. We felt like he had never done a WFOE before either. Turns out, that was close to the truth. He subcontracted the paperwork to another local agent (Aaron Best), who actually presented at the first Hacker Camp…

sz-credit-registration

Eventually we looked up the agent’s company registration. It isn’t even a WFOE. It appears he had two Chinese people start the company so he wouldn’t have to put up the 10 million RMB capital he registered. If you’re talking to an agent in Shenzhen, be sure to look up the company on the official SZ government business listing to confirm who you’re working with. Here’s our registration.

The agent said the company could be done in a month, but in all it took 4-5 months to complete this initial setup phase. Much of the delay was our own complicated situation because we’re an existing, functioning company. A competent agent would have foreseen and guided, instead ours made everything much, much worse. We paid the guy $7000, which includes lots of government fees.

Get your stuff together

Capital

capital-injection

Up until this year you needed 500,000RMB ($81,000USD) of actual cash to start a trading WFOE. There are no hard limits now, but you have to convince the government you can run your company for a year with that amount.

Everyone says minimum 100,000RMB if you want a work visa. Agents terrified us with likely untrue anecdotes about being deemed unfeasible, so we put up 400,000RMB fully paid. Supposedly this is enough to get 4-5 work permits for foreign hackers to work in our Shenzhen office, but who knows if that’s really true.

You need to prove that you have the full amount, but only 20% needs to be transferred up front. The remaining 80% can be paid over the next 2 years. At least that’s what they say, it seems really unfeasible for a small company because each payment takes weeks of processing documents and updating licenses.

bank-reference

A bank reference letter and a certified balance statement prove you have the capital. Hang Seng’s phone bank sent us to the nearest branch to apply in person, somewhat conveniently located in the bank district of a dusty little boarder town called Sheung Shui. The first Hong Kong metro stop outside China.

The banker insisted, INSISTED, there was no such thing as a bank reference letter OR certified balance statement. After 10 minutes of begging, they uncovered the form for the reference letter, but not the balance statement.

More begging and pleading, but they insisted that there was no such thing and threw us out.  The next day the phone banker sent us the form by email to print and take to the branch. Got the same guy, but no apology for making us schlep back to Hong Kong a second time.

Both letters run about $50 each, and are available for pickup after 10 business days.

Director documents

secondpassport

The director of the company needs to supply a passport. The passport will be out of reach for a reasonably long time, many months, so it is absolutely critical that you get a second valid passport if allowed in your country. It is quite easy in the US, all the Shenzhen regulars seem to have them.

The passport will need to be authenticated. The deal here is that China is not part of the Apostille Convention that defines how most countries translate and verify documents.

Authentication is a 1900s era flair of ribbons and wax stamps. The US State Department verifies the passport and makes a copy. The Chinese embassy in the US verifies the State Department copy with a ribbon.  Back in China the government verifies the embassy ribbon with a wax stamp. Or something like that. $1000USD for this frilly anachronism.

Hong Kong company documents

hk-greenbox

All the Hong Kong company “green box” stuff needs to be authenticated by a lawyer (7000HKD/$1000USD). If you have a brand new Hong Kong company the documents are already authenticated, but ours was a year old and it all had to be redone.

hk-greenbox-hack

Speaking of green box, we added a magnetic reed switch and RGB LEDs to ours. Nothing says “business” like a company box with a party mode to celebrate the signing (chopping) of a contract. So far bankers and lawyers don’t seem to find it as amusing as we do.

hkvisa

Expert tip: when signing documents in Hong Kong a copy of your entry visa slip is required. If you’re smart and have the second passport you MUST enter Hong Kong on the passport used to register the Hong Kong company. Our agent neglected to tell us about this, so we had to make two trips.

audit-report

If the Hong Kong company is more than a year old China wants to see an audit report completed by a CPA. Hong Kong companies are required to file an audit report with the Hong Kong government every year anyways, but as a little perk the first is due after 18 months. Everybody knows this, all the agents use it as a selling point.

Dangerous Prototypes Limited (HK) fell into the gap – not old enough to need a report in HK, but old enough to need one in China. Instead of pointing this out and helping us deal with it, our idiot agent said our accountant had failed to file the report on time and we would have to pay fines and could even go to jail. He got us whipped up into a frothy lather and scared the hell out of us.

Nope, just needed to get the audit report done early. The audit took two weeks and cost about $500USD from a Chinese accounting firm with an office in Hong Kong. Submit a Google-translated Chinese copy of the report as well.

Officespaced

office-door

A WFOE office must be at least 30 square meters in commercial zoned space, not an apartment. Agents terrified us with myths about inspections, verification, losing visas, and bribing inspectors, so we were needlessly married to having a big office in Huaqiangbei.

HQB-map

We looked at a lot of offices in three buildings. SEG at the south, the Mr. Goodluck Buy building (not actual name) mid-market, and Galaxy Stars building at the North of the market. Offices run about 100RMB per square meter, plus building fees and tax.

seg
The office is going to sit empty for half a year while the company is formed, so we wanted to pay about $1000USD per month (6000RMB). There were lots of too small offices in the 4000RMB range, and there were lots of really big multi-room offices for 10,000RMB+, but not a whole lot for us.

mrgoodluckbuy

The Mr. Goodluck Buy building is unique. Its owned entirely by one company. That’s easier for a WFOE to work with, and there’s no charge for upgrading to a bigger office in the same building later.

qunxin

We ended up in Galaxy Stars Plaza, the building at the very north end of the market with a helicopter landing pad. No, we haven’t been to the helipad. Yes, we’ve tried. Several times.

Galaxy Stars is the Chung King Mansion of Huaqiangbei offices, a Mos Eisley Cantina of little Chinese trading companies. Perfect place for us, and our logistics company is just a floor below.

office

Initially we had rental agents show us space, but they run you all around unable to get inside any of the offices. Its a joke. Asking the security guard on duty to show us around was much more effective. He found us a perfect 52 square meter office for 6000RMB/month including fees and taxes.

building-tax

The contract needs to say that the owner allows the office to be used for a WFOE. Everyone exchanges ID copies, and they hand over a copy of the building tax license. The contract needs a realtor stamp to be official, the guard found someone to provide it.

China’s clean government

National_Emblem_of_the_Peop

One theme throughout the formation process is that agents tell myths, stories, legends, “conventional wisdom”, and seemingly outright lie about stuff. One agent came into our office and said it wasn’t big enough, he was confident the work visa officer would review the floor plan and ask for a bribe. Image source.

Never, during this entire process, was there even a HINT of corruption in the Shenzhen government. Absolutely everything was by the books and squeaky clean. Follow the rules, file paperwork, wait, repeat. There wasn’t even a remote opportunity for something improper to happen.

Part of our motivation for writing this in such long form is to show how clean the experience was. The only corruption and incompetence we experienced was from agents.

The numbers man

An accounting firm is mandatory. The amount of paperwork they file monthly is epic.

China has two levels of sales tax/VAT. A small tax payer pays 3% VAT on everything purchased, and it cannot be refunded when things are exported or sold.

A general tax payer owes 17% VAT on everything they buy, but the tax is refunded when the stuff is exported out of China.

We have been both, currently we’re general tax payers and that was a horrible, horrible mistake. We haven’t done a VAT refund from exporting PCBs yet, it will be interesting to see what happens.

Accounting prices are the same all over town. 400RMB ($70USD) per month for a small tax payer, 1100RMB ($180USD) for a general tax payer. 50RMB ($9USD) per month per Chinese employee, and 150RMB ($29USD) per month per foreigner. Our accounting firm is acceptable, if a little lazy.

The process

complete-docs-pile

Got all that stuff now? It took us 3 months to get everything in order before filing the first document with the government.

Name check (2 weeks)

name-search

Submit a bunch of Chinese names, the government will pick their favorite. There are all sorts of naming rules. Ours shook out to Shenzhen Hanging from the Cliff’s Edge Electronics Technology Limited Company. “Hanging from the Cliff’s Edge” is the actual translation of Xuan Yaun, which is a close as we could get to “Dangerous”.

Foreign Ownership Certificate (4 weeks)

foreign-invest-cert

Here’s where that Foreign Owned part really clicks. The Hong Kong company applies to the government for permission to open a company in China. China gives us this giant certificate redeemable for one Chinese company. Now we’re getting somewhere.

foreign-invest-details

Notice it says for investors from Hong Kong, Macau, and Taiwan? That’s because it belongs to the Hong Kong company, not us.

Business license (10 days)

cn-company-license

All the documents and the company coupon go the local government. 10 days later we get a business license and a copy. These giant papers will have to be folded and carried a ridiculous number of places over the next several months.

company-permission

We also get a half dozen permission letters from the local government. They want one every time we get permits, a bank account, visas, etc, etc.

The problem with stamps

stamps

So, China enjoys stamps. You need them endlessly. The company has three stamps: general stamp, financial stamp, and customs stamp.

KNOW IT: Domestic company stamps are round, WFOE stamps are oval. Are they really a WFOE? Check their stamp!

personal-stamp

We each have name stamps as well. Literally just a stamp with English names.

During the next phase everyone needs the stamps: accountants, permit and licensing agents, visa agents, the bank. Of course you’re gonna need a little stamp time of your own too.

Here’s the rub: you only get one stamp and its illegal to copy them. Part of what takes so damn long with the WFOE is waiting for stamp time. For a while our stamps were couriered between 6 offices almost daily. This can’t be how Tencent deals, can it?

Mix and serve over ice

This is just the initial setup. To actually do anything with the company we still need a bank license and account (2 months), an import-export license (1 month), a work visa (3 months), and a couple other things. We’ll write these up in less-epic posts in the coming weeks.

Was it worth it? No idea yet. The dust is settling though, and we can see a day in the future when we’re running the company instead of starting it.