Web3 Beginner Series: Exploring New On-Chain Payment Protocols - x402

CN
4 hours ago

Coinbase announced a new payment protocol a few days ago: x402. Since x402 is initiated by Coinbase, it naturally supports Base Sepolia and is available by default. It has also provided support for the Solana chain, proving that x402 is not bound to a specific chain.

https://github.com/coinbase/x402

To clarify the process, I created a new repository (https://github.com/gin-lsl/x402-solana-demo) that contains all the Server, Client, and Facilitator components. Here, I chose Koa as the base framework, allowing the client to pay with USDC (a custom token) on Devnet to gain access to a specific interface provided by the server.

Some Explanations

First, I used the spl-token tool to create the corresponding token, which can be viewed here: https://solscan.io/token/9gKBTRXgVTszU31A12oJKKSy6aje8LyoVvNfSimembHo?cluster=devnet

I chose Solana because this chain is very developer-friendly, providing almost unlimited test tokens for everyone to develop and test. It does not set any thresholds, does not require login, does not require binding any social accounts, and does not require the wallet to have a balance on the mainnet.

To run the project, you need to create a .env file and fill in the required environment variables, then start the server and run the client code in the terminal:

Code Explanation

Since this is just for demonstration purposes, I simply placed them in the same location. Below are some main file explanations:

solana.ts

It provides a "/solana/get-balance" interface, which we assume is a valuable interface that requires a small payment to call. As the Server role, it corresponds to parts (5) ~ (8) in the sequence diagram, specifically (7).

Typically, the Server only involves handling business requirements and does not need to deal with on-chain transaction logic. Therefore, if a developer of a certain system does not understand Web3, they can still integrate Web3 payment methods with minimal changes to their business code.

facilitator.ts

It implements the capabilities of the Facilitator, mainly providing the /supported, /verify, and /settle interfaces, which are used to query the currently supported chains, verify transaction data, and handle on-chain settlement capabilities. This is where interaction with the chain occurs, requiring a private key to pay for on-chain transaction fees. It is architecturally independent of the Server (i.e., solana.ts), corresponding to parts (9) and (10) in the sequence diagram.

Even if you decide to provide the Facilitator service yourself, this part of the code is actually standardized and can be used directly with the official provided model without needing to implement it yourself. However, currently, the official support is only complete for Base; if you want to use other chains, some adaptation work is needed. This mainly involves sending simulated transactions to the chain to verify transactions (if it is a chain already supported by "x402", you can directly call the verify function) and formally submitting transactions to the chain and waiting for final confirmation (if it is a chain already supported by "x402", you can directly call the settle function).

For the Solana chain, after the request reaches POST /settle, it calls the settle function in "x402/facilitator", which, after some verification, calls sendTransaction on the RPC to send the transaction, and then waits for and confirms the transaction result using waitForRecentTransactionConfirmation, with the involved code provided by @solana/kit. The EVM part follows a similar logic.

x402-middleware.ts

This is used to link the Server and Facilitator together. It acts as a Koa middleware that guards interfaces that require payment to call, with code referencing the official "x402-express". Its function is to automatically return a 402 status and forward /verify and /settle requests.

In this part of the code, I mainly assembled various parameters and forwarded them to the facilitator or returned them to the client. For convenience in testing and to avoid involving too many details, I set most parameters to fixed values. These include:

  • Setting maxAmountRequired to a very large value, which will actually be validated in the client; if the amount the user needs to pay exceeds this, an exception will be thrown.
  • Setting the asset to our own created Token: 9gKBTRXgVTszU31A12oJKKSy6aje8LyoVvNfSimembHo, rather than the built-in Token address in x402. On the mainnet, it should be the official address of USDC.

Interestingly, x402-express achieves a Koa-like onion model by overriding functions on the Response. So in their middleware for express, the actual flow is verify -> business logic -> settle. Submitting to the chain occurs after executing the business logic, which indeed aligns with the sequence diagram above. Implementing this logic in Koa is very simple, while in Express, it requires some additional code, which may be why they prioritized providing the express middleware.

payment-client-fetch.ts

Acts as the client role, initiating requests to the server, corresponding to steps 1 ~ 4 in the flowchart. It uses helper functions provided by "x402-fetch" to automatically handle 402 statuses, generate signatures using the client's wallet private key, and resend requests, etc.

It will attempt to directly request the interface, and upon encountering a 402 error, it will read the returned content (which should include the x402 version supported by the server, currently fixed at 1, as well as the required parameters), sign the transaction with your private key, and then serialize the transaction information to resend it to the original URL via the X-PAYMENT Header.

After understanding the basic structure of the project, we can run the Server and Client with the following command:

Client execution results and logs:

Thoughts

I personally believe that if the efforts made by Web3 developers before were aimed at lowering the threshold for ordinary users to use Web3, making it easier for end users to engage with the Web3 ecosystem (payments, investments, etc.), then the current x402 is born to lower the threshold for Web2 developers to integrate Web3 payment channels.

The helper functions provided in the x402/client part are useful but only do what they are supposed to do. Now users can conveniently pay with USDC and others through wallets. Therefore, relatively speaking, x402 may hold greater significance for developers and service providers.

However, the widespread application of x402 will still encounter many issues. Some large companies have internal settlement systems and will have their own attitudes and rhythms regarding how to integrate new standards. Integrating a new payment method into their existing systems will undoubtedly require a long journey. Additionally, large companies must consider regulatory impacts when integrating payments, which may lead them to abandon more convenient payment methods in favor of complex traditional solutions.

Perhaps Node RPC providers will favor it more; in addition to providing basic interfaces, RPC providers also offer many Advanced APIs, transaction acceleration interfaces, etc. If this part can be provided through x402, it may allow more people to experience their services.

Finally, please note that x420 itself is just a basic payment protocol; its significance lies in proposing a standardized technical standard. With a recognized standard, it will be easier for developers and various large, medium, and small companies to work together to improve the entire ecosystem based on the standard. We should view the introduction of new standards rationally and avoid falling into the narrative traps set by speculators.

This article was written by ZANTeam (X account @zan_team).

免责声明:本文章仅代表作者个人观点,不代表本平台的立场和观点。本文章仅供信息分享,不构成对任何人的任何投资建议。用户与作者之间的任何争议,与本平台无关。如网页中刊载的文章或图片涉及侵权,请提供相关的权利证明和身份证明发送邮件到support@aicoin.com,本平台相关工作人员将会进行核查。

Share To
APP

X

Telegram

Facebook

Reddit

CopyLink